EntityFramework 6中的查询优化

时间:2014-12-16 10:53:01

标签: c# sql-server performance entity-framework

在分析我的应用程序(和数据库)时,我在分析器中发现了一个巨大的查询(大约200行),如下所示:

exec sp_executesql N'SELECT 
    [Project2].[UserID] AS [UserID], 
    ---
    FROM ( SELECT 
        [Limit1].[UserID] AS [UserID], 
         --- 
       CASE WHEN ([Extent4].[MemberID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
        FROM   (SELECT TOP (1) 
            [Extent1].[UserID] AS [UserID], 
            ---
            FROM   [MST].[User] AS [Extent1]
            INNER JOIN [FW].[Role] AS [Extent2] ON [Extent1].[RoleID] = [Extent2].[RoleID]
            LEFT OUTER JOIN [MST].[Society] AS [Extent3] ON [Extent1].[SocietyID] = [Extent3].[SocietyID]
            WHERE [Extent1].[UserName] = @p__linq__0 ) AS [Limit1]
        LEFT OUTER JOIN [MST].[Member] AS [Extent4] ON [Limit1].[UserID] = [Extent4].[UserID]
    )  AS [Project2]
    ORDER BY [Project2].[UserID] ASC, [Project2].[RoleID1] ASC, [Project2].[SocietyID2] ASC, [Project2].[C1] ASC',N'@p__linq__0 varchar(8000)',@p__linq__0='xxx'

查询的来源是 -

var d1=db.Users.Include("Role").Include("Society").Include("Members").First(m => m.UserName == username);

我可以通过将代码分成四个不同的语句来实现(不确定正确的EF方式)

var data = db.Users.First(m => m.UserName == username);
var x = data.Role;
var y = data.Society;
var z = data.Members;

生成四个精简查询:

exec sp_executesql N'SELECT TOP (1) 
    [Extent1].[UserID] AS [UserID], 
    ---
    WHERE [Extent1].[UserName] = @p__linq__0',N'@p__linq__0 varchar(8000)',@p__linq__0='xxx'
go

exec sp_executesql N'SELECT 
    [Extent1].[RoleID] AS [RoleID], 
    ---
    FROM [FW].[Role] AS [Extent1]
    WHERE [Extent1].[RoleID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=16
go

exec sp_executesql N'SELECT 
    [Extent1].[SocietyID] AS [SocietyID], 
    ---
    WHERE [Extent1].[SocietyID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=6
go

exec sp_executesql N'SELECT 
    [Extent1].[MemberID] AS [MemberID], 
    ---
    FROM [MST].[Member] AS [Extent1]
    WHERE [Extent1].[UserID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=19
go

因此,为了提高性能(并减少维护开销),构建EF查询的更好方法是什么?

0 个答案:

没有答案