EF一对多的条件

时间:2016-05-19 02:43:37

标签: c# .net entity-framework linq

我使用Entity Framework

生成了以下两个类
public class Persons
{
    public string Name { get; set; }
    public int personId { get; set; }   
    //NAVIGATIONL PROP. 
    public virtual ICollection<streetLivedIn> { get; set; }
}

public class StreetLivedIn
{      
    public string Address1 { get; set; }
    public string AddressType { get; set; }
   //NAVIGATIONL PROP. 
    public virtual PersonId (Foriegn Key with Person)
}

Person和Street Lived In之间存在一对多关系。我正在尝试提取AddressTypestreetlivedin表中为“Home”的人员列表。为此我有以下声明

var Lstpersons = db.persons()
                   .Include(x => x.streetlivedin)
                   .Where(x => x.streetlivedin.AddressType == "Home");

上面的代码在where子句中引发错误,说它无法将ICollection<streetlivein>转换为streetlivedin类。

我想知道如何使用Include和where.And使用Persons上下文来实现这一点。(我知道可以使用streetLivedIn上下文轻松实现它。 喜欢

var Lstpersons = db.streetlivedin()
                   .Include(x => x.person)
                   .Where(x => x.streetlivedin.AddressType == "Home");

(没有加入声明......请)

3 个答案:

答案 0 :(得分:2)

您正试图找到streetlivedin.AddressType == "Home",但streetlivedin是个人实体的集合。而是在streetlivedin上执行子查询,例如:

var Lstpersons = db.persons()
                   .Include(x => x.streetlivedin)
                   .Where(x => x.streetlivedin.Any(y=>y.AddressType == "Home"));

答案 1 :(得分:1)

int id=1;
var Lstpersons=(from s in db.streetlivedins  where s.AddressType == "Home" && s.PersonId ==id select s).ToList();

如果您不想要特定的用户地址

var Lstpersons=(from s in db.streetlivedins  where s.AddressType == "Home" select s).ToList();

如果你想要人

var Lstpersons=(from p in db.persons  let st =p.streetlivedins from s in st where s.AddressType == "Home" select p).ToList();

答案 2 :(得分:1)

为了让所有人只有他们的家庭住址,你需要一个像这样的查询。

from person in db.persons()
join address in db.streetlivedin() on person.personId equals address.PersonId
where address.AddressType == "Home"
select new { Person = person, HomeAddress = address }

当然,由于这是一个内部联接,任何拥有多个家庭住址的人在结果中都会出现不止一次。

顺便说一下,如果我不得不使用该代码库,混合大写会让我感到疯狂。您不必遵循C#编码约定,但如果您要选择自己的约定至少使其保持一致。