c# - EF 包含列表始终为空
问题描述
由于某种原因,EF 不会正确加载包含的列表,因此它最终始终为空。
这是我正在使用的实体:
[Table("searchprofilepush")]
public class SearchProfilePush
{
public int Id { get; set; }
public int AccountId { get; set; }
public bool Push { get; set; }
public int UserPushId { get; set; }
public UserPush UserPush { get; set; }
public int SearchProfileId { get; set; }
public SearchProfile SearchProfile { get; set; }
public ICollection<SearchProfileMediaTypePush> SearchProfileMediaTypePush { get; set; }
}
[Table("searchprofilemediatypepush")]
public class SearchProfileMediaTypePush
{
public int Id { get; set; }
public MediaTypeType MediaType { get; set; }
public bool Push { get; set; }
public int SearchProfilePushId { get; set; }
public SearchProfilePush SearchProfilePush { get; set; }
}
然后当我尝试这样做时:
var searchProfilePush = _dataContext.SearchProfilePush.Include(w => w.SearchProfileMediaTypePush).FirstOrDefault(w => w.AccountId == accountId && w.SearchProfileId == searchProfileId);
我的包含列表始终为空。
我想这是为什么这不起作用的一些明显原因,但我就是想不通。
谢谢!
编辑:这是 sql 查询:
SELECT \"Extent1\".\"id\", \"Extent1\".\"accountid\", \"Extent1\".\"push\", \"Extent1\".\"userpushid\", \ "Extent1\".\"searchprofileid\" FROM \"public\".\"searchprofilepush\" AS \"Extent1\" WHERE \"Extent1\".\"accountid\" = @p__linq__0 AND @p__linq__0 不为空并且(\"Extent1\".\"searchprofileid\" = @p__linq__1 AND @p__linq__1 不为空) 限制 1
编辑 2:我现在已经映射了我的实体,并且列表仍然始终为空。
编辑3:
解决方案
我阅读的加载相关实体的文档与示例代码和您的代码有一些差异。https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx
首先,当您定义 ICollection 时,没有关键字 virtual:
public virtual ICollection<SearchProfileMediaTypePush> SearchProfileMediaTypePush { get; set; }
接下来,在靠近您的示例中,他们使用查询加载相关项目,第一个或默认不使用布尔表达式。选择性表达式在 where 子句中:
// Load one blogs and its related posts
var blog1 = context.Blogs
.Where(b => b.Name == "ADO.NET Blog")
.Include(b => b.Posts)
.FirstOrDefault();
所以你可以试试:
var searchProfilePush = _dataContext.SearchProfilePush
.Where(w => w.AccountId == accountId && w.SearchProfileId == searchProfileId)
.Include(w => w.SearchProfileMediaTypePush)
.FirstOrDefault();
你能做这两个改变,然后再试一次吗?
推荐阅读
- xamarin - 升级后 MvxListView 中的 ListItems 与 MvvmCross 6.4.1 中的 Items 绑定不一致
- ios - 如何明智地裁剪图像形状?
- python - 根据 pandas 中的约束生成列
- node.js - Nodejs CRUD + 使用 Postman 进行测试
- c# - 在统一 C# 中从脚本执行 NGUI 按钮按下
- android - 我们可以从 WebApp 发出通知吗?
- javascript - 如何使用javascript验证输入是否为可读日期格式
- docker - Docker 将驱动程序和中间件安装到容器中
- amazon-web-services - AWS 每个项目是否提供免费套餐?
- clojure - Clojure 中带有映射的函数参数