【发布时间】: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