You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 3模型创建时如何插入一对多关系的实体数据?

问题解决方法

错误的原因是你在OnModelCreating中尝试访问Publishers集合,而此时EF Core正处于模型构建阶段,DbContext还不能被用来查询或访问关联的实体集合。

要实现书籍与出版社的关联,你需要直接使用出版社的主键ID来设置外键,而不是通过导航属性Publisher赋值。具体步骤如下:

  1. 确保Book实体包含对应的外键属性(如果还没有的话):
public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public DateTime Created { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }
    
    // 添加外键属性
    public int PublisherId { get; set; }
    // 导航属性保留
    public Publisher Publisher { get; set; }
}
  1. 修改OnModelCreating中的HasData代码,直接指定PublisherId的值:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Publisher>().HasData(
                new Publisher { Id = 1, Name = "Ciela" },
                new Publisher { Id = 2, Name = "Knigomania" },
                new Publisher { Id = 3, Name = "Bard" },
                new Publisher { Id = 4, Name = "Labyrinth" },
                new Publisher { Id = 5, Name = "Emgont" },
                new Publisher { Id = 6, Name = "Bloomsbury" }
                );

    modelBuilder.Entity<Book>().HasData(
                new Book
                {
                    BookId = 1,
                    Title = "book",
                    Author = "a",
                    Created = DateTime.UtcNow,
                    Quantity = 1,
                    Price = 5,
                    // 直接指定出版社的ID,而不是导航属性
                    PublisherId = 3
                });
}

这样就能正确建立书籍和出版社的关联,同时避免模型构建阶段的错误。因为HasData是在数据库初始化时插入种子数据,直接使用主键ID关联是最可靠的方式,EF Core会自动处理外键关系。

内容的提问来源于stack exchange,提问作者ayhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:12:05