当我执行这个SQL语句时,它绝对没有时间运行:
select * from [user]
left join licence on [user].userID = licence.UserID
left join licenceProducts on licence.licenceID = licenceProducts.licenceID
left join products on products.productID = licenceProducts.productID
left join contacts on contacts.UserID = [user].userID
left join usersupportedproducts on usersupportedproducts.UserID = [user].userID
left join [user] b on b.userID = [user].ParentUserID
where [user].Type <> 6
order by [user].name
但是,当我使用EF 4.0运行相同的查询时,执行将花费将近20秒。
有没有办法改进这个Linq请求,我试过了?
users = null;
using (var db = new DistributorEntities())
{
try
{
users = db.Users
.Include(u => u.Licences)
.Include(u => u.Licences.Select(l => l.LicenceProducts.Select(lp => lp.Product)))
.Include(u => u.UserAddress)
.Include(u => u.Contact)
.Include(u => u.User2)
.Include(u => u.SupportProducts)
.Where(u => u.Type != (int)UserType.Admin)
.OrderBy(u => u.Name)
.ToList();
}
catch (Exception ex)
{
if (ex is InvalidOperationException)
{
_EventLog.WriteEntry(ex.Message + " WebService.GetAllUsersAndChildren");
}
exception = new ServiceError(ex);
}
}
我尝试通过放置我的SQl语句来执行ExecuteStoreQuery()
,但它没有加入users
的关系。
答案 0 :(得分:1)
直接在SQL中编写查询几乎总是比在LINQ中编写表达式更有效,然后必须将其转换为&#34;次优的&#34; SQL。
您可以做的只是创建一个包含您的查询的VIEW
,然后将VIEW
映射到实体框架中的Entity
,然后查询Entity
- 这将只执行SQL Server中的VIEW
。
另见http://www.mssqltips.com/sqlservertip/1990/how-to-use-sql-server-views-with-the-entity-framework/。