2015-03-02 176 views
0

如何將SQL查詢轉換爲LINQ? 你能幫我把下面的SQL查詢翻譯成LINQ嗎?將SQL查詢轉換爲LINQ

SELECT Top 1 @SalesRepID = Part.KUNN2 
FROM x Part with(nolock) 
JOIN y UserCustomer with(nolock) 
ON Part.KUNN2 = UserCustomer.Customer 
LEFT JOIN z[User] with(nolock) 
ON UserCustomer.UserId = [User].UserId 
AND [User].UserDisabled != 'Y' 
WHERE (Part.PARVWxx = 'ZP' or Part.PARVWxx = 'ZR') 
AND Part.KUNNRxx = @Customer 
ORDER BY Part.KUNNRxx, Part.PARVWxx DESC 
+1

你使用的是實體框架嗎?顯示你到目前爲止。 – 2015-03-02 23:24:18

+0

您使用的是什麼ORM?實體框架,NHibernate,Linq到SQL等 – JNYRanger 2015-03-03 00:37:00

+0

我正在使用實體框架。 – Siv 2015-03-03 19:55:10

回答

0

您可以在這裏玩如下:https://dotnetfiddle.net/wcqLUx它可能不是你所需要的東西;它會讓你開始雖然。我需要做一些假設;你可以在小提琴中清除那些。以下是20分鐘左右我能做的最好的。

void Main() 
{ 
    IEnumerable<User> Users = 
     new List<User> { new User { UserId = 0, UserDisabled = "N" } }; 
    IEnumerable<Part> Parts = 
     new List<Part> { new Part { SalesRepId = 0, PARVWxx = "ZP", KUNNRxx = "@Customer" } }; 
    IEnumerable<UserCustomer> UserCustomers = 
     new List<UserCustomer> { new UserCustomer { UserId = 0, Customer = 0 } }; 

    var query = 
     from p in Parts 
     join y in UserCustomers 
     on p.SalesRepId equals y.Customer 
     select new { p, y } into inner 
      join z in Users 
      on inner.y.UserId equals z.UserId 
      where ! z.UserDisabled.Equals("Y") && 
      inner.p.PARVWxx.Equals("ZP") && 
      inner.p.KUNNRxx.Equals("@Customer") 
      select inner.p.SalesRepId; 

    foreach(var result in query) 
    { 
     Console.WriteLine(result); 
    } 
} 

// Define other methods and classes here 
public class Part 
{ 
    public int SalesRepId { get; set; } 
    public string PARVWxx { get; set; } 
    public string KUNNRxx { get; set; } 
} 

public class User 
{ 
    public int UserId { get; set; } 
    public string UserDisabled { get; set; } 
} 

public class UserCustomer 
{ 
    public int UserId { get; set; } 
    public int Customer { get; set; } 
}