T-SQL到LINQ查询(多对多过滤器)

时间:2015-05-18 08:07:07

标签: c# linq tsql

我有与客户有多对1的查询。查询还有许多对残疾人的编码。我想做的是收集所有包含某些残障代码的查询的唯一客户。这是我的T-SQL:

SELECT DISTINCT ClientId FROM (
   SELECT ce.Id as EnquiryId, dc.Code, c.Id as ClientId
      FROM ClientEnquiryToDisabilityCodes as etd
      INNER JOIN DisabilityCodes as dc
      ON etd.ClientEnquiryToDisabilityCode_DisabilityCode = dc.Id
      INNER JOIN ClientEnquiries as ce
      ON etd.ClientEnquiryToDisabilityCode_ClientEnquiry = ce.Id
      INNER JOIN Clients as c 
      ON ce.ClientEnquiry_Client = c.Id
      WHERE dc.Code = 'Ast') 
AS data

有人甚至可以开始向我展示如何将其变成LINQ吗?我甚至不知道从哪里开始。谢谢。

2 个答案:

答案 0 :(得分:0)

这并不像我初想的那么困难。在开始工作之前我应该​​喝更多的咖啡!

var distinctcients = (from etd in Context.ClientEnquiryToDisabilityCodes
                                  join dc in Context.DisabilityCodes on etd.ClientEnquiryToDisabilityCode_DisabilityCode equals dc.Id
                                  join ce in Context.ClientEnquiries on etd.ClientEnquiryToDisabilityCode_ClientEnquiry equals ce.Id
                                  join c in Context.Clients on ce.ClientEnquiry_Client equals c.Id
                                  where dc.Code == DisabilityCode
                                  select c.Id)
                                 .Distinct().ToList();

答案 1 :(得分:0)

鉴于您已在下方附加了类结构,Example方法将实现您的尝试

void Example()
{
    var clients = new DisabilityCode[1].Where(dc      => dc.Code == "Ast")
                                       .SelectMany(dc => dc.Enquiries)
                                       .Select(etd    => etd.ClientEnquiry)
                                       .Select(ce     => ce.Client.ClientId);
                                    //     or
                                    // .Select(ce     => ce.Client)
                                    // .Select(c      => c.ClientId);

}

public class DisabilityCode
{
    public string DisabilityId { get; set; }
    public string Code { get; set; }
    public virtual ICollection<ClientEnquiryToDisabilityCode> Enquiries { get; set; }
}

public class ClientEnquiry
{
    public string ClientEnquiryId { get; set; }
    public string ClientId { get; set; }

    public virtual Client Client { get; set; }
    public virtual ClientEnquiryToDisabilityCode DisabilityCode { get; set; }
}

public class ClientEnquiryToDisabilityCode
{
    public string ClientEnquiryId { get; set; }
    public string DisabilityCodeId { get; set; }

    public virtual ClientEnquiry ClientEnquiry { get; set; }
    public virtual DisabilityCode DisabilityCode { get; set; }
}

public class Client
{
    public string ClientId { get; set; }
    public virtual ICollection<ClientEnquiry> Enquiries { get; set; }
}