c# - EF 一对多 where 条件

标签 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 之间存在一对多关系。我正在尝试拉出一个人的列表,其 AddressType , 在 streetlivedin表,是“家”。为此,我有以下声明

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");

(没有连接语句....请)

最佳答案

您正在尝试查找 streetlivedin.AddressType == "Home" 的位置,但 streetlivedin 是个人实体的集合。相反,在 streetlivedin 上做一个子查询,例如:

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

关于c# - EF 一对多 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37313088/

相关文章:

c# - WCF REST 错误处理 - 不正确的输入

c# - ASP.net 中的浏览器滚动条(如何设置)

c# - 在基于 MVVM 的应用程序中管理分层对象状态的最佳方法/方法是什么?

c# - 如何使用 HttpWebRequest 使 HTTP 请求通过匿名 NTLM 进行身份验证

c# - 如何防止 C# 中因无效输入而崩溃

.net - 如何在数据库优先方法中进行迁移

c# - 值不能为空。参数名称 : type

c# - 为什么不允许为方法声明空表达式体?

c# - 如何从列表中获取最后一条记录

c# - 通过 C# 将 JSON 数据 POST 到 PHP 并将值存储在 MYSQL 中