tin*_*ker 13 c# entity-framework entity-framework-core
我正在创建一个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>();
}
Run Code Online (Sandbox Code Playgroud)
当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();
Run Code Online (Sandbox Code Playgroud)
现在,这很好用,但你可以看到我打了.Include(u = u.Posts)两次电话.有没有办法ThenInclude在同一个属性上调用两次,而没有实际写Include两次语句?
Jan*_* Go 39
现在,这种方法很好,但是你可以看到我正在调用.Include(u = u.Posts)两次.有没有办法在同一属性上调用ThenInclude两次,而实际上也没有两次写Include语句?
调用Include(u => u.Posts)两次是正确的方法.
来自EF Core docs ...强调最后一句话.
您可能希望为其中一个实体包含多个相关实体.例如,查询时
BlogS,你有Posts,然后想以包括Author和Tags的Posts.为此,您需要指定从根开始的每个包含路径.例如,Blog -> Posts -> Author和Blog -> Posts -> Tags.这并不意味着您将获得冗余连接,在大多数情况下,EF将在生成SQL时合并连接.
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.Include(blog => blog.Posts)
.ThenInclude(post => post.Tags)
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5676 次 |
| 最近记录: |