使用LINQ编写SQL查询

时间:2014-08-05 11:29:40

标签: c# linq

到目前为止,我有这个:

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)

请注意,GROUPADDRESS是具有GROUPSAddresses的{​​{1}}和Group_K表之间的桥接表 我无法弄明白如何添加新的Address_K查询或更新我必须为我要添加的新LINQ帐户添加的查询。谢谢你的帮助。

SQL

2 个答案:

答案 0 :(得分:1)

也许是这样的:

var groupID=1;
var groupTaxId=1;
var result=
(
    from a in this.Context.ADDRESSES
    where
    (
        from ga in this.Context.GROUPADDRESS
        join g in this.Context.Groups
            on g.GROUP_K equals ga.GROUP_K
        where ga.ID == groupID
        where g.TaxId== groupTaxId
        where ga.ACTIVE == 1
        select ga.ADDRESS_K
    ).Contains(a.ADDRESS_K)
    select new
    {
        a.zipCode
    }
).ToList();

答案 1 :(得分:1)

假设您的上下文中有一个GroupAddress:

var query = (from g in this.Context.Groups
join ga in this.Context.GroupAddress on g.AddressK equals ga.AddressK
where g.ID == groupID &&
      g.TaxId == groupTaxId
select g.Group_K);

编辑:

正确,因此GroupAddress位于Group和Address之间。假设您已在数据库中设置关系,您将拥有可以测试的导航属性:

where g.Address == ''

EF删除链接表,以便您的导航更简单。如果在EF中不可用,请在上面添加另一个连接。

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