如何在 MVC 中检测或处理空查询结果

本文关键字:处理 查询 结果 检测 MVC | 更新日期: 2023-09-27 17:57:14

下面的代码适用于以下情况:信用卡表中已存在已登录用户的记录;但是,当用户在信用卡表中没有条目时,查询将按预期查找零条记录。 问题是,语句 maxccid = 查询。Maxccid();返回 Null 并引发无效操作异常。我无法使数据库中的 ccid 字段为空,因为它是主键的一部分。 我需要一种方法来检测此查询是否会在我运行它之前返回 null,或者一种方法来捕获它(最好没有 try catch,因为这种情况将发生在每个新客户身上(Try/Catch 的最佳实践声明这不是 Try/Catch 的正确用法)。 只是要补充一点,我正在使用实体框架。

更新 4/9/14:我修改了查询以修复我在评论中向 Usesr FailedProgramming 和 Mike 报告的问题。 不过,我仍然有空问题。

// Create CreditCard - Write to DB
    public ActionResult Create(CreditCard model)
    {
        EntitiesContext context = new EntitiesContext();
        int uid = (int)WebSecurity.GetUserId(User.Identity.Name);  // Currently logged-in user
        short? maxccid = 0; //this will be the max ccid for this user
        var query = from c in context.CreditCards
                    where c != null && c.UserId == uid select c.CCID;
        maxccid = query.Max();

如何在 MVC 中检测或处理空查询结果

if(query.Any())
     maxccid = query.Max();

首先对 databse 对象使用 using
其次,使用零合并运算符。用于处理空
值 在此处检查 http://msdn.microsoft.com/en-us/library/ms173224.aspx

public ActionResult Create(CreditCard model)
{
    using(EntitiesContext context = new EntitiesContext()) // using keyword will dispose the object properly.
    {
        int uid = (int)WebSecurity.GetUserId(User.Identity.Name);  // Currently logged-in user
        short? maxccid = 0; //this will be the max ccid for this user
        var query = from c in context.CreditCards 
                where c.UserId == uid && c.CCID == (context.CreditCards.Max(c1 => c1.CCID) ) select c.CCID ;
        maxccid = query.Max() ?? 0; //use null-coalescing operator.
    }

}

您可以根据需要进一步优化此代码。希望,它可能会在某个时候帮助你。有好的一天。