首页 > 解决方案 > 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:

这就是我创建数据库表的方式。 在此处输入图像描述

标签: c#postgresqlentity-frameworkasp.net-core

解决方案


我阅读的加载相关实体的文档与示例代码和您的代码有一些差异。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(); 

你能做这两个改变,然后再试一次吗?


推荐阅读