سؤال

العام الماضي، سكوت جوثري معلن "يمكنك في الواقع تجاوز SQL الخام الذي يستخدمه LINQ to SQL إذا كنت تريد التحكم المطلق في SQL الذي يتم تنفيذه"، لكن لا يمكنني العثور على وثائق تصف طريقة التوسعة.

أرغب في تعديل LINQ التالي إلى استعلام SQL:

using (NorthwindContext northwind = new NorthwindContext ()) {
    var q = from row in northwind.Customers
            let orderCount = row.Orders.Count ()
            select new {
                row.ContactName,
                orderCount
            };
}

مما يؤدي إلى TSQL التالي:

SELECT [t0].[ContactName], (
    SELECT COUNT(*)
    FROM [dbo].[Orders] AS [t1]
    WHERE [t1].[CustomerID] = [t0].[CustomerID]
    ) AS [orderCount]
FROM [dbo].[Customers] AS [t0]

ل:

using (NorthwindContext northwind = new NorthwindContext ()) {
    var q = from row in northwind.Customers.With (
                        TableHint.NoLock, TableHint.Index (0))
            let orderCount = row.Orders.With (
                        TableHint.HoldLock).Count ()
            select new {
                row.ContactName,
                orderCount
            };
}

أيّ كان يؤدي إلى TSQL التالي:

SELECT [t0].[ContactName], (
    SELECT COUNT(*)
    FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK)
    WHERE [t1].[CustomerID] = [t0].[CustomerID]
    ) AS [orderCount]
FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0))

استخدام:

public static Table<TEntity> With<TEntity> (
    this Table<TEntity> table,
    params TableHint[] args) where TEntity : class {

    //TODO: implement
    return table;
}
public static EntitySet<TEntity> With<TEntity> (
    this EntitySet<TEntity> entitySet,
    params TableHint[] args) where TEntity : class {

    //TODO: implement
    return entitySet;
}

و

public class TableHint {
    //TODO: implement
    public static TableHint NoLock;
    public static TableHint HoldLock;
    public static TableHint Index (int id) {
        return null;
    }
    public static TableHint Index (string name) {
        return null;
    }
}

استخدام نوع ما من LINQ إلى SQL القابلية للتوسعة، بخلاف هذا.أيه أفكار؟

هل كانت مفيدة؟

المحلول

إن القدرة على تغيير الموفر الأساسي وبالتالي تعديل SQL لم تؤدي إلى القطع النهائي في LINQ إلى SQL.

نصائح أخرى

تحتوي مدونة Matt Warren على كل ما تحتاجه لذلك:

http://blogs.msdn.com/mattwar/

تريد ترجمة شجرة التعبير إلى SQL ...تحتاج إلى تنفيذ IQueryProvider الخاص بك

مرجع IQueryProvider
كيف

كيفية استخدام MSDN

DataContext x = DataContext جديد؛

// ربما شيء من هذا القبيل؟

var a = x.Where().with()...إلخ

دعونا يكون لديك سيطرة أفضل بكثير على SQL.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top