Using DbContext Set<T>() instead of exposing on the context

寵の児 提交于 2019-11-27 21:54:20

The Users property is added for convenience, so you don't need to remember what all of your tables are and what the corresponding class is for it, you can use Intellisense to see all of the tables the context was designed to interact with. The end result is functionally equivalent to using Set<T>.

You get a benefit with the former method when using Code-First migrations, as new entities will be detected as such automatically. Otherwise, I'm quite certain they are equivalent.

This is how I set my generic dbSet, works just fine

DbContext context = new MyContext();
DbSet<T> dbSet = context.Set<T>();

It is the generic version of something more explicit, such as

DbContext context = new MyContext();
DbSet<User> dbSet = context.Set<User>();

Either way, they are the same (when T is User)

I think there is some difference. Let me use the example as in the question. Assume i want to do a Any based on User.FirstName and User.LastName (User table has more fields)

Method1: UsersContext.Users.Any(u => u.FirstName.ToLower() == userObj.FirstName && u.LastName.ToLower() == userObj.LastName);

Method2: (UsersContext.Set(typeof(User)) as IQueryable<User>).Any(u => u.FirstName.ToLower() == userObj.FirstName && u.LastName.ToLower() == userObj.LastName);

I checked in sql profiler the query fired in Method1 is:

    exec sp_executesql N'SELECT 
CASE WHEN ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[User] AS [Extent1]
    WHERE (((LOWER([Extent1].[FirstName])) = (LOWER(@p__linq__0))) AND ((LOWER([Extent1].[LastName])) = @p__linq__1)
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[User] AS [Extent2]
    WHERE (((LOWER([Extent2].[FirstName])) = (LOWER(@p__linq__0))) AND ([Extent2].[LastName] = @p__linq__1)
)) THEN cast(0 as bit) END AS [C1]
FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]',@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)',@p__linq__0=N'jack',@p__linq__1=N'saw'

From Method2:

    SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[LastName] AS [LastName], 
[Extent1].[Email] AS [Email], 
.......other fields......
FROM [dbo].[Users] AS [Extent1]

The table has 40000 records and Method1 takes around 20 ms while Method2 takes around 3500 ms.

Behnam Esmaili

I think there is no such difference between two approaches except that Set<User>() is more suitable for implementing data access patterns like Repository pattern because of the generic nature of the Set<T>() method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!