EF Core FindAsync仅返回根对象

时间:2019-01-02 16:46:49

标签: c# entity-framework .net-core

我有很多关系,并且我正在使用带有EF的ASP.Net Core2.2 MVC。

据我了解,目前我必须为联接表创建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; }
}

DBContext:

 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();

创建帖子时,我可以在数据库中看到我有帖子数据,并且在PostCategory表中,我可以看到应有的PostId CategoryId。

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

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

post。类别计数始终为0,我缺少什么?

1 个答案:

答案 0 :(得分:0)

您需要按以下方式编写查询,以期用Categories加载相关的Post

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

这是有关Loading Related Data in EF core

的更多详细信息