如何编写基于EF的linq查询?

时间:2009-11-13 19:33:19

标签: linq entity-framework

假设我有三个表:

Person(pid, ...)
PersonAddress(pid, aid,...)
Address(aid, ...)

然后我想得到像sql这样的人物地址:

select a.* from address a join PersonAddress pa on a.addressID=pa.addressID 
where pa.personID = myPersonID

使用Entity Framework创建实体模型,然后想要像上面的sql编写一个linq等价物。

我按照以下方式尝试了它:

 var addresses = this.GetAddress();
        var personaddresses = this.GetPersonAddress();

        var query = from ad in addresses
                    from pa in personaddresses
                    where ((ad.AddressID == pa.AddressID)&&(pa.PersonID==person.personID))
                    select ad;

但我收到了错误。或者我尝试从:

开始
var result = this.Context.Address;
var result = result.Join ....  //how to write linq in this way?  

如何编写linq?

3 个答案:

答案 0 :(得分:2)

这是未经测试的,但是如果您已经设置了所有关系并且您创建了模型(我已使用Model作为此名称),那么您应该能够使用以下内容:

var values = this.Model.Address.Select(a => a.PersonAddress.Where(pa => pa.Id == myPersonID));

答案 1 :(得分:1)

您几乎从未在LINQ to Entities中使用join

尝试:

var q = from p in Context.People
        where p.PersonId == personId
        from a in p.Addresses // presumes p.Addresses is 1..*
        select a;

答案 2 :(得分:1)

假设您有三个实体:Person,PersonAddress和Address,这里是一个满足您需求的查询(此示例假定一个名为context的实体框架上下文):

var values = context.PersonAddress.Where(pa => pa.Person.PersonId == myPersonId).Select(pa => pa.Address);

但是,如果PersonAddress表作为纯粹的多对多关系表存在(即仅包含键),那么最好以中间表不是这样的方式设置Entity Framework模型必要的,这会让你更简单:

var values = context.Person.Where(p => p.PersonId == myPersonId).Addresses;

根据其他反馈

因为您需要包含国家/地区表,所以您应该从Address表中发起您的查询。在那种情况下:

var values = context.Address.Where(a => a.PersonAddress.Where(pa => pa.Product.Id == myProductId).Count() > 0)

要在结果中包含Country表:

var values = context.Address.Include("Country").Where(a => a.PersonAddress.Where(pa => pa.Product.Id == myProductId).Count() > 0)