c# - 从表中获取最大值,除非为空

标签 c# asp.net-mvc

我对 C# 和 ASP.NET(以及一般的编程)还很陌生,尝试做一些简单的练习。

我正在尝试做的事情: 我想构建一个简单的 MVC 应用程序,其中记录将有版本。 即:给定一条记录,我将通过“编辑”- View 进行更改,该记录将不会被覆盖。相反,将创建一个新记录(如新版本)。新旧记录都具有相同的 ItemId(这不是主键!),将它们“语义”链接在一起。为了知道哪个记录是较新的 Version,较新记录的 VersionId 是旧记录的 VersionId +1。

目前:我已经开始研究 Create-Action。新记录的 VersionId 的值应为 1,而 ItemId 的值应为数据库中已有的最大 ItemId 加 1 - 除非数据库中没有记录,在这种情况下,ItemId 应为 1。

模型:

namespace HowToUpdate.Models
{
    public class ItemWithVersion
    {
        public int Id { get; set; }
        public int ItemNr { get; set; }
        public int VersionNr { get; set; }
        public string Name { get; set; }
    }
}

Controller 操作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name")] ItemWithVersion itemWithVersion)
    {
        if (ModelState.IsValid)
        {
            // set the ItemNr
            int currentMaxItemNr = db.ItemWithVersions.Max(i => i.ItemNr);
            itemWithVersion.ItemNr = currentMaxItemNr + 1;

            // set the VersionNr
            itemWithVersion.VersionNr = 1;

            db.ItemWithVersions.Add(itemWithVersion);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(itemWithVersion);
    }

问题:当我运行 localhost/ItemWithVersion/Create 时,为名称输入一个值并提交,我收到以下错误: “转换为值类型‘System.Int32’失败,因为物化值为空。结果类型的通用参数或查询必须使用可为空的类型。 源错误:int currentMaxItemNr = db.ItemWithVersions.Max(i => i.ItemNr);"

我试过了:

// set the ItemNr
int currentMaxItemNr = db.ItemWithVersions.Max(i => i.ItemNr);          
if (currentMaxItemNr == null)
{
    itemWithVersion.ItemNr = 1;
}
else
{
    itemWithVersion.ItemNr = currentMaxItemNr + 1;
}

现在错误似乎是 int currentMaxItemNr = db.ItemWithVersions.Max(i => i.ItemNr);

还有 int? currentMaxItemNr = db.ItemWithVersions.Max(i => i.ItemNr);var currentMaxItemNr = db.ItemWithVersions.Max(i => i.ItemNr); 不会做任何事情好。

这可能很基础,但我需要你的帮助! :) 谢谢。

最佳答案

你的 if 语句是错误的:

if (currentMaxItemNr != null) 当前检查 currentMaxItemNr 是否有值,如果有,则将其设置为 1

所以你的声明应该是if (currentMaxItemNr == null)

编辑:

不幸的是,我无法复制您的错误,但我确实检查并发现在空 List 上调用 Max() 时会抛出异常。所以最好先调用 if (db.ItemWithVersions.Count() > 0)

这样你就可以确定 Max() 会返回一个结果。如果该语句失败,您可以将 currentMaxItemNr 设置为 0

关于c# - 从表中获取最大值,除非为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34658580/

相关文章:

c# - 我可以拦截通过 HTTP 上传到 IIS7 的文件并根据验证标准拒绝上传吗?

c# - 带有 ODP.Net Oracle.ManagedDataAccess 的 EF 6,如何对类属性使用非大写字母?

c# - .net C# 中的 LDAP 连接

c# - 进度条MVVM?

c# - 在 C# 中使用 ICU 类和方法

c# - ASP.NET MVC5,两个 Controller ,在不同的文件夹中具有相同的名称

asp.net-mvc - Controller 中的方法重载

c# - 简单的数字正则表达式不起作用

c# - 显示上传到服务器的图片

asp.net-mvc - 在整数属性上使用 NotEmpty 进行流畅验证