Linq(实体框架)vs SQL用于动态数据分页

时间:2012-03-11 14:05:07

标签: c# asp.net sql linq c#-4.0

我一直在寻找使用Entity Framework从SQL TableAdapters切换到Linq,但是有些元素阻止了我,同时也让我生气。

我有一个ASP.NET 4.0 C#VS2010项目站点。

我的要求如下:

  • 数据必须可分页
  • 数据必须动态订购(即ORDER BY SelectedColumnName ASC / DESC)
  • 数据必须基于网页控件,文本框,下拉菜单等进行过滤。再次,动态。
  • 返回的列必须是可动态构造的
  • 使用大型表必须尽可能地响应。分页有助于此。
  • 在前端记录中必须显示信息。即“显示记录1-20 of 100”“第5页,共20页”等
    • Project仅是内部可访问的网站。不在互联网上或任何东西。

根据我的要求,我开始使用System.Linq.Dynamic命名空间查看Dynamic Linq。我取得了一些成功,但很大程度上我的疑问变得过于复杂。

根据我的要求,是否有任何真正的理由使用Linq和Entity Framework与标准SQL?

据我所知,标准SQL通过我能理解和控制的查询语言为我提供了所需的所有控件。 Linq是一种我并不十分熟悉的语言,并且不允许我像我需要的那样将所有元素开箱即用。

回到使用SQL存储过程/表适配器进行查询会不会错?

我从Linq实验中学到的一件事是,通过代码隐藏控制属性可以更好地控制信息,因此我可以使用这些数据来解析存储过程,以便将数据输入到网格视图中。

这是我正在使用的Linq表达式的一个示例:

private void FetchData()
{
    using (var Context = new ProjectEntities())
    {
        string Fields = GetDynamicFields();

        var Query =
            Context.Users
            .Join(Context.UserStats,            // Table to Join
                u => u.msExchMailboxGuid,       // Column to Join From
                us => us.MailboxGuid,           // Column to Join To
                (u, us) => new                  // Declare Columns for the next Join
                {
                    ObjectGuid = u.objectGuid,
                    msExchMailboxGuid = u.msExchMailboxGuid,
                    CompanyName = u.CompanyName,
                    ResellerOU = u.ResellerOU,
                    DisplayName = u.DisplayName,
                    MBXServer = u.MBXServer,
                    MBXSG = u.MBXSG,
                    MBXDB = u.MBXDB,
                    MBXWarningLimit = u.MBXWarningLimit,
                    MBXSendLimit = u.MBXSendLimit,
                    MBXSendReceiveLimit = u.MBXSendReceiveLimit,
                    extensionAttribute10 = u.extensionAttribute10,
                    legacyExchangeDN = u.legacyExchangeDN,
                    UserPrincipalName = u.UserPrincipalName,
                    Mail = u.Mail,
                    lastLogonTimeStamp = u.lastLogonTimestamp,
                    createTimeStamp = u.createTimeStamp,
                    modifyTimeStamp = u.modifyTimeStamp,
                    altRecipient = u.altRecipient,
                    altRecipientBL = u.altRecipientBL,
                    DeletedDate = u.DeletedDate,
                    MailboxGuid = us.MailboxGuid,
                    Date = us.Date,
                    AssociatedItemCount = us.AssociatedItemCount,
                    DeletedItemCount = us.DeletedItemCount,
                    ItemCount = us.ItemCount,
                    LastLoggedOnUserAccount = us.LastLoggedOnUserAccount,
                    LastLogonTime = us.LastLogonTime,
                    StorageLimitStatus = us.StorageLimitStatus,
                    TotalDeletedItemSize = us.TotalDeletedItemSize,
                    TotalItemSize = us.TotalItemSize,
                    MailboxDatabase = us.MailboxDatabase
                })
            .Join(Context.TechContacts,         // Table to Join
                u => u.UserPrincipalName,       // Column to Join From
                tc => tc.UPN,                   // Column to Join To
                (u, tc) => new                  // Declare Final Column Names
                {
                    ObjectGuid = u.ObjectGuid,
                    msExchMailboxGuid = u.msExchMailboxGuid,
                    CompanyName = u.CompanyName,
                    ResellerOU = u.ResellerOU,
                    DisplayName = u.DisplayName,
                    MBXServer = u.MBXServer,
                    MBXSG = u.MBXSG,
                    MBXDB = u.MBXDB,
                    MBXWarningLimit = u.MBXWarningLimit,
                    MBXSendLimit = u.MBXSendLimit,
                    MBXSendReceiveLimit = u.MBXSendReceiveLimit,
                    extensionAttribute10 = u.extensionAttribute10,
                    legacyExchangeDN = u.legacyExchangeDN,
                    UserPrincipalName = u.UserPrincipalName,
                    Mail = u.Mail,
                    lastLogonTimeStamp = u.lastLogonTimeStamp,
                    createTimeStamp = u.createTimeStamp,
                    modifyTimeStamp = u.modifyTimeStamp,
                    altRecipient = u.altRecipient,
                    altRecipientBL = u.altRecipientBL,
                    DeletedDate = u.DeletedDate,
                    MailboxGuid = u.MailboxGuid,
                    Date = u.Date,
                    AssociatedItemCount = u.AssociatedItemCount,
                    DeletedItemCount = u.DeletedItemCount,
                    ItemCount = u.ItemCount,
                    LastLoggedOnUserAccount = u.LastLoggedOnUserAccount,
                    LastLogonTime = u.LastLogonTime,
                    StorageLimitStatus = u.StorageLimitStatus,
                    TotalDeletedItemSize = u.TotalDeletedItemSize,
                    TotalItemSize = u.TotalItemSize,
                    MailboxDatabase = u.MailboxDatabase,
                    // New Columns from this join
                    UPN = tc.UPN,
                    Customer_TechContact = tc.Customer_TechContact,
                    Customer_TechContactEmail = tc.Customer_TechContactEmail,
                    Reseller_TechContact = tc.Reseller_TechContact,
                    Reseller_TechContactEmail = tc.Reseller_TechContact,
                    Reseller_Name = tc.Reseller_Name
                })
            .Where(u => true)
            .OrderBy(GlobalVars.SortColumn + " " + GlobalVars.SortDirection)
            .Select("New(" + Fields + ")");

        // Add Extra Filters
        if (!(string.IsNullOrWhiteSpace(SearchCompanyNameTextBox.Text)))
        {
            Query = Query.Where("CompanyName.StartsWith(@0)", SearchCompanyNameTextBox.Text);
        }

        // Set the Record Count
        GlobalVars.TotalRecords = Query.Count();

        // Add Paging
        Query = Query
            .Skip(GlobalVars.Skip)
            .Take(GlobalVars.Take);

        // GridView Datasource Binding
        GridViewMailboxes.DataSource = Query;
        GridViewMailboxes.DataBind();
    }
}

这是通过SQL查询做同样事情的一个例子:

DECLARE @SQLSTATEMENT NVARCHAR(4000);
DECLARE @FieldList varchar(MAX);
DECLARE @OrderBy varchar(100);
DECLARE @OrderDirection varchar(100);
DECLARE @PageSize int;
DECLARE @StartRow int;

SET @FieldList = 'u.UserPrincipalName, u.Mail, us.TotalItemsize, tc.UPN';
SET @OrderBy = 'u.CompanyName';
SET @OrderDirection = 'ASC';
SET @PageSize = 20;
SET @StartRow = 80;

SET @SQLSTATEMENT = '
SELECT TOP(@PageSize) * FROM
(
SELECT ' + @FieldList + ' 
,row_number() OVER (ORDER BY @OrderBy ' + @OrderDirection + ') AS [row_number]
FROM Users As u
INNER JOIN UserStats as us
ON u.msExchMailboxGuid = us.MailboxGuid
INNER JOIN TechContacts AS tc
ON tc.UPN = u.UserPrincipalName
) AS r
WHERE r.[row_number] > @StartRow '

EXEC sp_executesql @SQLSTATEMENT,
N'@FieldList varchar(MAX), @OrderBy varchar(100), @OrderDirection varchar(100), @PageSize int, @StartRow int',
@FieldList, @OrderBy, @OrderDirection, @PageSize, @StartRow

我很欣赏这是一个悬而未决的问题,如果我能让它更清楚,我当然会。但是,考虑到我的要求,我很难看到在我的情况下使用Linq的好处。 Linq似乎并不擅长编写完全动态的查询,并且可能必须在任何地方执行SQL(因此SQL更快?)。

我已经构建了前端控件,可以将我需要的全部内容解析为globalvars,然后我可以使用它来调用数据:

    public class GlobalVars
    {
        public static int TotalRecords = 0;
        public static int TotalPages = 0;
        public static int CurrentPage = 0;
        public static int LowerPage = 0;
        public static int UpperPage = 0;
        public static int Take = 0;
        public static int Skip = 0;
        public static string SortColumn = "CompanyName";
        public static string SortDirection = "Ascending";
    }

1 个答案:

答案 0 :(得分:3)

使用存储过程总是会更快。

另外,我确定你可以看到,事实上,更容易理解你的SQL代码,而不是Linq。

实际上你的意思是在你的代码的sql语句中调用它。 即使这样,它也更容易阅读。在一天结束时,他们会产生同样的事情。

Linq很适合查询所有准备好的列表。

例如,您有一个列表,但现在需要匹配WHERE x = y的对象和新列表WHERE x = z您可以在不重新查询数据库的情况下执行此操作。

如果你要去数据库,使用sql查询就可以了。如果有必要,LINQ可以使用它来进一步操作列表。

有些人可能不同意,但一切都归结为prefence。我个人称他们使用SQL代码语句。