将SQL查询转换为LINQ 2 SQL表达式

时间:2010-06-16 19:19:22

标签: sql linq-to-sql

如何将以下SQL查询重写为其等效的LINQ 2 SQL表达式(在C#和VB.NET中)

    SELECT t1.itemnmbr, t1.locncode,t1.bin,t2.Total
        FROM  IV00200 t1 (NOLOCK)
                     INNER JOIN
              IV00112 t2 (NOLOCK)
                 ON  t1.itemnmbr = t2.itemnmbr 
                 AND t1.bin = t2.bin
                 AND t1.bin = 'MU7I336A80'

1 个答案:

答案 0 :(得分:3)

编辑:我注意到你要求C#和VB.Net,所以我添加了一个VB示例。

<强> C#

using (var txn = new TransactionScope(
    TransactionScopeOption.Required, 
    new TransactionOptions
    {
        IsolationLevel = IsolationLevel.ReadUncommitted
    }
))
{
    var results = from t1 in db.IV00200 
                  join t2 in db.IV00112 
                    on new { t1.itemnmbr, t1.bin }
                    equals new { t2.itemnmbr, t2.bin }
                  where t1.bin == 'MU7I336A80'
                  select new {t1.itemnmbr, t1.locncode, t1.bin, t2.Total};

    // Do something with your results

}

<强> VB.Net

Dim results
Dim transOptions = New TransactionOptions
transOptions.IsolationLevel = IsolationLevel.ReadUncommitted

Using txn As New TransactionScope(TransactionScopeOption.Required, transOptions)
    results = From t1 In db.IV00200 _
              Join t2 In db.IV00112 _
                On New With {.itemnmbr = t1.itemnmbr, .bin = t1.bin} _
                Equals New With {.itemnmbr = t2.itemnmbr, .bin = t2.bin} _
              Where t1.bin = "MU7I336A80" _
              Select New With {.itemnmbr = t1.itemnmbr, .locncode = t1.locncode, .bin = t1.bin, .Total = t2.Total}

    ' Do something with your results

End Using

您需要将System.Transactions添加到项目的引用中。 TransactionScope块在原始查询中重新创建nolock条件。

[TransactionScope / NoLock来源:http://madprops.org/blog/linq-to-sql-and-nolock-hints/]