【发布时间】:2018-11-26 14:26:02
【问题描述】:
我正在创建一个 ASP.NET Core API 应用程序,并依赖于 EF Core。我有这样定义的实体:
public class AppUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
[InverseProperty(nameof(Post.Author))]
public ICollection<Post> Posts { get; set; } = new List<Post>();
}
public class Post
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string AuthorId { get; set; }
[ForeignKey("AuthorId")]
public virtual AppUser Author { get; set; }
[InverseProperty(nameof(Like.Post))]
public ICollection<Like> Likes { get; set; } = new List<Like>();
[InverseProperty(nameof(Comment.Post))]
public ICollection<Comment> Comments { get; set; } = new List<Comment>();
}
其中Comment 和Like 是其他一些实体。请注意,为简洁起见,我已经简化了实体。然后,我想获取用户的Posts,还包括帖子获得的Likes 和Comments。所以,我做了这样的事情:
return _context.Users
.Include(u => u.Location)
.Include(u => u.Posts)
.ThenInclude(p => p.Comments)
.ThenInclude(c => c.Owner)
.Include(u => u.Posts)
.ThenInclude(p => p.Likes)
.ThenInclude(l => l.Giver)
.Where(u => u.Id == userId)
.FirstOrDefault();
现在,这可以正常工作,但正如您所见,我调用了两次 .Include(u = u.Posts)。有没有办法在同一属性上调用ThenInclude 两次,而实际上又不写两次Include 语句?
【问题讨论】:
标签: c# entity-framework entity-framework-core