I need to check if customer by code already exists in the database using entity framework. Ideally I would write plain sql query like this:
select id from dbo.Customer where RecActive = 1 and Code = 'xxx';
If query result is empty, it means customer by code 'xxx' does not exist yet. In entity framework there are multiple ways to write this, but I'm looking the one nearest above. Note: Code field has unique index on it
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();
}
Perhaps any other good (performance alternative)? Note: I have to use entity framework linq and not raw queries (which I would really like) as linq is used throughout whole project consistently.
Codeis the primary key EF will perform the check itself before inserting or updating. If you want to check for existence for some other reason useAny(). If you want the ID use.Where()...).Select(c=>c.id)<condition> ? true : false- seems redundant to me.Any()will likely useselect nullin its query and rather thanselect id. It's a very minor difference, but the question is round about in both asking that it matches that minor inefficiency of the original query and also asking that it be the most performant.