2

我对搜索人有相当复杂的看法。有几个链接表,如地址、电话、电子邮件、会员资格等。该视图名为 vSeachMember,实体也是如此。

如果我像这样在 SQL Mgmt Studio 中运行查询:

Select * FROM vSearchMember WHERE FirstName like '%kelly%'

它在大约 2 秒内运行并且有大约 160,000 次读取(使用 sql profiler 找到)

如果我使用 EF 在我的 MVC 应用程序中运行此代码(_db 是上下文):

var p = _db.vSearchMembers.Where(p => p.FirstName.Contains("kelly") ).ToList();

大约需要 25 秒,有 12,000,000 次读取。

我试图预先生成我的观点,但没有帮助。我也试过关闭延迟加载。有任何想法吗?谢谢。

EF生成的代码:

exec sp_executesql N'SELECT 
[Extent1].[Id] AS [Id], 
...
FROM (SELECT  
[vSearchMember].[Id] AS [Id],
...     
FROM [dbo].[vSearchMember] AS [vSearchMember]) AS [Extent1]
WHERE ( CAST(CHARINDEX(LTRIM(RTRIM(@p__linq__0)), [Extent1].[FirstName]) AS int)) =
1',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'kelly'

为简洁起见,上面的“...”被省略了,它只是每个字段的语法相同(其中 29 个)。

4

1 回答 1

1

Check the SQL that EF is generating. Separate the query from the extraction in your code like so and breakpoint on the second line

var query = vSearchMembers.Where(p => p.FirstName.Contains("kelly") )
var p = query.ToList();

You can get the SQL by inspecting query.

I don't know why, but willing to bet it's quite different to your hand-coded SQL query.

Interested to see vSearchMembers DDL.

FURTHER EDIT:

Just to make the code in the comment a bit more readable, can you try something like this:

var members = db.Members.Where(p => p.FirstName.Contains("kelly");
var query = from m in members
            from s in vSearchMembers.Where(s => s.MemberId == m.MemberId)
            select s;
var p = query.ToList();
于 2013-03-07T18:25:31.570 回答