【问题标题】:How can I detect or handle a Null Query result in MVC?如何在 MVC 中检测或处理空查询结果?
【发布时间】:2014-04-10 05:18:44
【问题描述】:

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

更新 4/9/14:我修改了查询以解决我在 cmets 中向用户 FailedProgramming 和 Mike 报告的问题。我仍然有 null 问题。

// 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();

【问题讨论】:

  • if(query.Any()) maxccid = query.Max(); 怎么样

标签: c# entity-framework asp.net-mvc-4


【解决方案1】:
if(query.Any())
     maxccid = query.Max();

【讨论】:

  • 谢谢迈克尔。这对我不起作用。很奇怪,但是如果 creditCard 表中有三个或更多记录,它会按我的预期执行 (query.Any()) 为真,否则如果有一两条记录,它等同于假,这不是我想要的.如果查询返回一条或多条记录,我认为 query.Any() 应该返回 true?
  • 我仍在努力,但我认为这是迈克尔的工作。我之前认为不是,但我在查询中发现了一个错误。
【解决方案2】:

首先对数据库对象使用using
其次,使用空合并运算符。用于处理 null
在这里查看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.
    }


}

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

【讨论】:

  • Pratik,感谢您对此进行破解。当我输入 using(EntitiesConext.... 语句时,它会导致 context.CreditCards 语句不喜欢上下文(在所有引用的地方都用红色下划线)。
  • 问题是您只能在特定的 using 块中使用该上下文对象。你不能在范围之外使用它。做一件事不要使用那个使用,如果你不能得到它。只需使用空合并运算符,它会帮助你
  • Pratik,您不能对 short 或 int 类型的对象使用 Null Coalescing 运算符。代码按原样工作,但我发现查询没有产生一致的结果。当 CreditCards 表中只有 1 或 2 条记录时,query.Max() 返回 false 值。当有三个或更多 query.Max() 返回一个真值。这非常令人沮丧。我想知道它是否与EntityFramwork有关,因为我正在查询上下文,而不是直接查询数据库?
猜你喜欢
  • 2020-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 2018-08-11
  • 2018-03-06
相关资源
最近更新 更多