我有以下工作SQL查询:
select a.Id, a.Name
from Addresses a join Companies c
on c.AddressId = a.Id
or c.MailAddressId = a.Id
or c.Id = a.CompanyId
where c.Id = *CompanyId* and a.Name = *AddressName*
检查具有提供的地址名称的地址是否链接到具有提供的公司ID的公司。
如何在LINQ for EF中表达这一点?
更新:地址和公司类如下(仅包含与此问题相关的详细信息):
public class Address
{
public int Id {get; set;}
public string Name {get; set;}
public int? CompanyId {get; set;}
public virtual Company {get; set;}
}
public class Company
{
public int Id {get; set;}
public string Name {get; set;}
public int AddressId {get; set;}
public virtual Address Address {get; set;}
public int? MailAddressId {get; set;}
public virtual Address MailAddress {get; set;}
public virtual ICollection<Address> DeliveryAddresses {get; set;}
}
谢谢。
答案 0 :(得分:2)
LINQ仅支持相等的连接。在其他情况下,您应该使用交叉连接,其中:
from a in Addresses
from c in Companies
where (c.AddressId == a.Id || c.MailAddressId == a.Id || c.Id == a.CompanyId)
&& (c.Id == *CompanyId* && a.Name == *AddressName*)
select new{a.Id, a.Name}