将SQL查询转换为LINQ

时间:2015-03-02 23:21:38

标签: c# 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 个答案:

答案 0 :(得分: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; }
}