实体框架 - 使用前检查单个记录的正确方法 [英] Entity Framework - Correct way to check for single records before using them

查看:67
本文介绍了实体框架 - 使用前检查单个记录的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要获取记录列表,我通常会按照以下方式执行某些操作:

To get a LIST of records I normally do something along the lines of:

var efCompany = from a in _dbRiv.Company where a.CompanyId == companyFeedInfo.CompanyId select a;

要获得单个记录,当我知道我正在使用PK检索它时,我使用某些东西喜欢:

To get a single record, when I know I am using the PK to retrieve it, I use something like:

var efCompany = (from a in _dbRiv.Company where a.CompanyId == companyFeedInfo.CompanyId select a).First();

现在,使用单记录方法,如果PK是有缺陷的值(如有目的地在测试)第二行会出现错误。

Now, using the single record approach, if the PK is a faulty value (like it purposefully is in testing) the 2nd line throws an error.

获得单个记录并处理该问题的最佳做法方式是什么? >

What is the best practice way of getting a single record and dealing with it?

推荐答案

如果您预期为0或1,则使用 SingleOrDefault ,或 FirstOrDefault 如果你只需要第一个可能很多的记录,但是可以处理0.两者都将返回类型的默认值(通常为null),如果没有结果。

Use SingleOrDefault if you expect 0 or 1, or FirstOrDefault if you just need the first record out of potentially many, but can cope with 0. Both will return the default value for the type (usually null) if there are no results.

顺便说一句,这样的查询通常使用查询表达式更可读(IMO)而不使用,因此您可能会有以下内容:

By the way, queries like this are generally more readable (IMO) without using a query expression, so you might have something like:

var efCompany = _dbRiv.Company
                      .Where(a => a.CompanyId == companyFeedInfo.CompanyId)
                      .SingleOrDefault();

if (efCompany != null)
{
    // Use it
}
else
{
    // Report to user, or whatever
}

当您使用多个操作符时,查询表达式非常好或者做相对复杂的事情,例如连接 - 但是如果你只是得到一个,其中子句或只是得到一个投影,这个点符号是更简单的IMO。当您需要调用最终的 FirstOrDefault 之类的方法时,效果会更好。

Query expressions are great when you're using multiple operators, or doing relatively complex things like joins - but if you've just got a where clause or just got a projection, this "dot notation" is simpler IMO. It also works better when you need to call a method like FirstOrDefault at the end.

这篇关于实体框架 - 使用前检查单个记录的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆