在LINQ中编写SQL查询

时间:2014-08-04 20:48:02

标签: c# linq linq-to-entities

到目前为止,我有这个:

var query = (from g in this.Context.Groups
    where g.ID == groupID &&
          g.TaxId == groupTaxId
    select g.Group_K);

然后我要添加的SQL查询是:

select zipCode from ADDRESSES where ADDRESS_K in 
(select ADDRESS_K from GROUPADDRESS 
       where GROUP_K = "is in Group_K found above "
       and address_type = "address type variable I pass into this method"
       and ACTIVE = 1)

我无法弄清楚如何添加新的LINQ查询或更新我必须为我要添加的新SQL帐户添加的查询。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

这个怎么样?

        var group_key = (from g in this.Context.Groups
            where g.ID == groupID
                  && g.TaxId == groupTaxId
            select g.Group_K);

        var query = (from a in this.Context.Addresses
            join ga in this.Context.GroupAddress on a.Address_K equals ga.Address_K
            where (group_key.Contains(ga.Group_K) && a.ZipCode == "whatever passed from method" && ga.Address_Type == "whatever passed from your method")
            select a);

答案 1 :(得分:0)

IN语句相当于LINQ to Entities中的Contains方法调用:

var query = from a in this.Context.Addresses
            where (from g in this.Context.Groups
                   where g.ID == groupID && g.TaxId == groupTaxId
                   select g.Group_K).Contains(a.Address_K);
            select a.ZipCode;

您还可以重写查询以使用JOIN而不是嵌套查询:

var query = from a in this.Context.Addresses
            join g in this.Context.Groups on a.Address_K equals g.Group_K
            where g.ID == groupID && g.TaxId == groupTaxId
            select a.ZipCode;