c# - 包含相关对象子集的属性

标签 c# asp.net-mvc entity-framework linq linq-to-entities

我有实体Post,它与Comment是一对多关系。我想要拥有只返回其中某些子集的属性:

public class Post
{

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<Comment> TopLevelComments
    {
        get
        {
            return Comments.Where(c => c.ParentID == null).ToList();
        }
    }
}

但是,此代码会抛出

ArgumentNullException: Value cannot be null. Parameter name: source

This answer似乎表明这是因为我在 Comments 仍为 null 时对其进行了过滤。然而,在使用这种方法的过程中,我确实急切地加载它:

var post = await _context.Post.Include(m => m.Author).Include(m => m.Comments).ThenInclude(m => m.Author).SingleOrDefaultAsync(m => m.PostID == id);

我怎样才能让它发挥作用?这是正确的方法吗?

最佳答案

首先,为了避免这种异常,您需要在空实体的构造函数中初始化集合属性:

public Post()
{
  Comment=new List<Comment>();
}

第二件事是使用 ThenInclude 表明您正在使用 EF Core。如果是这种情况,您必须使用预先加载,因为此版本的 EF 不支持延迟加载。

第三件事是 TopLevelComments 属性不应映射为模型的一部分:

 modelBuilder.Entity<Post>()
                .Ignore(b => b.TopLevelComments);

关于c# - 包含相关对象子集的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39457105/

相关文章:

asp.net - 模型更改检测 ASP.NET 代码优先迁移

c# - Iphone 移动应用程序中的圆形图像范围 (Xamarin.Ios/C#)

c# - 使用BackgroundWorker的请求似乎永远不会完成

asp.net - 在 Asp.net mvc5 中使用用户名而不是电子邮件作为身份

c# - 如何更新 EF 中的相关实体(代码优先)

c# - 如何使用带有 C# 的 Linq 在 Entity Framework 中获取多个结果集?

c# - 在 Unity iOS 上发出 HTTP 请求的方法?

c# - 如何在 FluentValidator C# 中验证枚举

asp.net-mvc - 使用 FormCollection 时,MVC 3 RTM allowedHtml 不起作用

asp.net-mvc - MVC 4 提供的防伪 token 适用于用户 "",但当前用户是 "user"