[英]Efficiently check if record exists in database using Entity framework LINQ
我需要使用實體框架檢查客戶的代碼是否已經存在於數據庫中。 理想情況下,我會像這樣編寫簡單的 sql 查詢:
select id from dbo.Customer where RecActive = 1 and Code = 'xxx';
如果查詢結果為空,則表示代碼'xxx'的客戶尚不存在。 在實體框架中,有多種方法可以編寫它,但我正在尋找最接近上面的一種。 注意:代碼字段上有唯一索引
using (var context = new CustomerContext())
{
// not very efficient as it reads all columns
return context.Customers.Where(c => c.RecActive && c.Code == customerCode).SingleOrDefault() != null ? true : false;
return context.Customers.Where(c => c.RecActive && c.Code == customerCode).Count() > 0 ? true : false;
// translates to this query:
// exec sp_executesql N'SELECT [Limit1].[Id] AS [Id]
// FROM ( SELECT TOP (2)
// [Extent1].[Id] AS [Id]
// FROM [dbo].[Customer] AS [Extent1]
// WHERE ([Extent1].[RecActive] = 1) AND (([Extent1].[Code] =
// @p__linq__0) OR (([Extent1].[Code] IS NULL) AND
// (@p__linq__0 IS NULL)))
// ) AS [Limit1]',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'xxx'
int a = context.Customers.Where(c => c.RecActive && c.Code == customerCode).Select(c => c.Id).SingleOrDefault();
return a > 0 ? true : false;
return context.Customers.Where(c => c.RecActive && c.Code == customerCode).Any();
}
也許還有其他好的(性能替代方案)? 注意:我必須使用實體框架 linq 而不是原始查詢(我真的很喜歡),因為 linq 在整個項目中始終如一地使用。
如果您只想檢查是否存在,請使用.Any()
。 如果要檢索符合條件的 ID,請使用Select
,例如:
context.Customers
.Where(c => c.RecActive && c.Code == customerCode)
.Select(c => c.id);
如果多個 ID 是有效結果,則無論id
的類型是什么,您的方法都應返回一個字符串/整數數組。 您可以使用.ToArray();
返回一個 ID 數組.ToArray();
return context.Customers
.Where(c => c.RecActive && c.Code == customerCode)
.Select(c => c.id)
.ToArray();
如果你不期望有多個 ID,你必須決定如果你得到多個結果怎么辦:
FirstOrDefault()
將返回第一個 ID 而不拋出。SingleOrDefault()
將拋出。例如:
return context.Customers.Where(c => c.RecActive && c.Code == customerCode)
.Select(c => c.id)
.SingleOrDefault();
由於您的代碼會忽略實際 ID,並且僅返回其存在的true
/ false
指示,因此您可以通過一次調用Any
:
return context.Customers.Any(c => c.RecActive && c.Code == customerCode);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.