【问题标题】:EF Core (Code First) unable to seed data in One To Many relationshipEF Core(代码优先)无法在一对多关系中播种数据
【发布时间】:2021-11-05 06:37:06
【问题描述】:

我正在尝试创建一个测验应用程序并且我有两个实体。 QuestionItem 和 AnswerItem。

一个问题可以有多个答案(一对多关系)。

这是我的模型。

public class TblQuestionItem
{
    //removing constructors to keep the code short

    [Key]
    public int QuestionID { get; set; }
    
    [Required]
    public string QuestionText { get; set; }

    public List<TblAnswerItem> AnswerList { get; set; }        
    
}

public class TblAnswerItem
{
    //removing constructors to keep the code short
    
    [Key]
    public int AnswerID { get; set; }
    
    [Required]
    public string AnswerText { get; set; }

    //this is required for foreign key relation 
    public int FkQuestionID { get; set; }
    public TblQuestionItem Question { get; set; }
}

这是我的上下文类

public class QuestionsDBContext : DbContext
{
    //Constructor
    public QuestionsDBContext(DbContextOptions<QuestionsDBContext> options) : base(options) { }

    public DbSet<TblQuestionItem> TblQuestions { get; set; }
    public DbSet<TblAnswerItem> TblAnswers { get; set; }

    //Seed initial data
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        //Configure One to Many relationship
        
        builder.Entity<TblAnswerItem>()
            .HasOne(c => c.Question)
            .WithMany(e => e.AnswerList)
            .HasForeignKey(p => p.FkQuestionID)
            .OnDelete(DeleteBehavior.Cascade);

        //Seed data
        TblQuestionItem Question1 = new TblQuestionItem(1, "Who is the CEO of SpaceX ?");
        
        TblAnswerItem Answer1 = new TblAnswerItem(1, "Jeff Bezos", 1, Question1);
        TblAnswerItem Answer2 = new TblAnswerItem(2, "Elon Musk", 1, Question1);
        TblAnswerItem Answer3 = new TblAnswerItem(3, "Bill Gates", 1, Question1);
        TblAnswerItem Answer4 = new TblAnswerItem(4, "Sundar Pichai", 1, Question1);            

        Question1.AnswerList.Add(Answer1);
        Question1.AnswerList.Add(Answer2);
        Question1.AnswerList.Add(Answer3);
        Question1.AnswerList.Add(Answer4);
                   
        builder.Entity<TblQuestionItem>().HasData(Question1);
       
        builder.Entity<TblAnswerItem>().HasData(Answer1);
        builder.Entity<TblAnswerItem>().HasData(Answer2);
        builder.Entity<TblAnswerItem>().HasData(Answer3);
        builder.Entity<TblAnswerItem>().HasData(Answer4);           

    }

}

现在,当我运行迁移时,我的期望是代码将在其中创建一个数据库和两个表,以及初始数据。但是迁移失败并出现错误:

The seed entity for entity type 'TblAnswerItem' cannot be added because it has the 
navigation 'Question' set. To seed relationships, add the entity seed to 'TblAnswerItem' 
and specify the foreign key values {'QuestionID'}. 
Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved 
property values.

我尝试了Here 提到的解决方案,但没有帮助。我在这里做错了什么?

【问题讨论】:

  • 尝试删除 TblAnswerItem 中 FkQuestionID 字段上的“Fk”前缀
  • @fatherOfWine 删除了 Fk,仍然出现同样的错误。
  • @BuggyCoder 我喜欢你的名字...干杯

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


【解决方案1】:

进行以下更改,它应该可以工作:

  1. 删除以下代码(无需填充导航属性):

     Question1.AnswerList.Add(Answer1);
     Question1.AnswerList.Add(Answer2);
     Question1.AnswerList.Add(Answer3);
     Question1.AnswerList.Add(Answer4);
    
  2. 从 TblAnswerItem 构造函数中删除 Question1 参数。与第 1 项中的推理相同。

【讨论】:

    【解决方案2】:

    我建议为你的默认数据定义一个类,这样更容易理解。

    首先我定义这个:

    public static class DefaultData
    {
        public static readonly List<TblQuestionItem> Questions = new List<TblQuestionItem>
        {
            new TblQuestionItem(1, "Who is the CEO of SpaceX ?")
        };
    
        public static readonly IEnumerable<TblAnswerItem> Answers = new TblAnswerItem[]
        {
            new TblAnswerItem(1, "Jeff Bezos", 1),
            new TblAnswerItem(2, "Elon Musk", 1),
            new TblAnswerItem(3, "Bill Gates", 1),
            new TblAnswerItem(4, "Sundar Pichai", 1)
    
        };
    }
    

    和 OnModelCreating 方法你 [MOST] 只需要像这样调用

    // seed data
    builder.Entity<TblQuestionItem>().HasData(DefaultData.Questions);
    builder.Entity<TblAnswerItem>().HasData(DefaultData.Answers);
    

    【讨论】:

      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多