0

当我执行这条 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);
    }
}

我试图ExecuteStoreQuery()通过放置我的 SQl 语句来执行,但它没有加入users.

4

1 回答 1

1

直接在 SQL 中编写查询几乎总是比在 LINQ 中编写表达式更有效,然后必须将其转换为“次优”SQL。

你可以做的是简单地创建一个VIEW包含你的查询,然后将它映射VIEW到一个Entity实体框架中,然后查询它Entity——它将只VIEW在 SQL Server 中执行。

另请参阅http://www.mssqltips.com/sqlservertip/1990/how-to-use-sql-server-views-with-the-entity-framework/

于 2013-10-31T13:46:55.997 回答