gpt4 book ai didi

c# - EF Core FindAsync 仅返回根对象

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:21 24 4
gpt4 key购买 nike

我有多对多关系,我正在使用 ASP.Net Core2.2 MVC 和 EF。

根据我的阅读,我了解到目前我必须为连接表创建一个 CLR 类。

我的代码:

模型:

public class Post
{
public Post()
{
Categories= new List<PostCategory>();
}
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public List<PostCategory> Categories { get; set; }
}

public class Category
{
public Category()
{
Posts= new List<PostCategory>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<PostCategory> Posts { get; set; }
}
public class PostCategory
{
public int PostId { get; set; }
public Post Post { get; set; }

public int CategoryId { get; set; }
public Category Category { get; set; }
}

数据库上下文:

 public class MyDBContext:DbContext
{
public MyDBContext()
{

}
public MyDBContext(DbContextOptions<MyDBContext> options) : base(options)
{

}
public DbSet<Post> Post { get; set; }

public DbSet<Category> Category { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostCategory>()
.HasKey(x => new { x.PostId, x.CategoryId });
modelBuilder.Entity<PostCategory>()
.HasOne(x => x.Post)
.WithMany(m => m.Categories)
.HasForeignKey(x => x.PostId);
modelBuilder.Entity<PostCategory>()
.HasOne(x => x.Category)
.WithMany(e => e.Posts)
.HasForeignKey(x => x.CategoryId);
}
}

创建邮政编码:

var categories= new List<PostCategory>();
foreach (var category in model.SelectedCategories)
{
categories.Add(new PostCategory()
{
CategoryId= category
});
}
model.Post.Categories.AddRange(categories);
_context.Post.Add(model.Post);
await _context.SaveChangesAsync();

当我创建一个帖子时,我可以在数据库中看到我有 Post 数据,并且在 PostCategory 表中我可以看到 PostId CategoryId,它们应该是这样的。

我的问题是当我尝试使用以下方式获取帖子数据时:

var post = await _context.Post.FindAsync(id);

post.Categories 计数始终为 0,我错过了什么?

最佳答案

您需要按如下方式编写查询,以便使用 Post 预先加载相关的 Categories:

var post =  await _context.Post.Include(p => p.Categories).FirstOrDefaultAsync(p => p.Id == id);

这里是关于 Loading Related Data in EF core 的更多详细信息

关于c# - EF Core FindAsync 仅返回根对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54010104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com