MVC 3,EF4,Code first DataBase Initializer错误

时间:2011-07-21 20:36:30

标签: asp.net-mvc-3 ef-code-first dbcontext

尝试使用初始化程序设置数据库时遇到了一些麻烦。我有3个表,LabTest-> LabValue< -LabIndicator,这就是我编码的方式:

public class LabTest
    {
        public int ID { get; set; }
        public DateTime ApplicationDate { get; set; }
        public virtual ICollection<LabValue> LabValues { get; set; }
    }

public class LabValue
    {
        public int ID { get; set; }
        public decimal Value { get; set; }
        public int LabTestID { get; set; }
        public int LabIndicatorID { get; set; }
        public virtual LabTest LabTest { get; set; }
        public virtual LabIndicator LabIndicator { get; set; }
    }

  public class LabIndicator
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public virtual ICollection<LabValue> LabValues { get; set; }
    }

这就是我在DBContext中编写Db Intializer的方法:

public class SummumnetDB : DbContext
{
  public DbSet<LabIndicator> LabIndicators { get; set; }
  public DbSet<LabTest> LabTests { get; set; }
  public DbSet<LabValue> LabValues { get; set; }

  public class MyFirstInitializer : DropCreateDatabaseIfModelChanges<SummumnetDB> 
  { 
     protected override void  Seed(SummumnetDB context)
     {
          new List<LabTest>
          {
               new LabTest{ ApplicationDate = DateTime.Now},
               new LabTest{ ApplicationDate = DateTime.Now},
          }.ForEach(l => context.LabTest.Add(l));

           new List<LabIndicator>
           {
                new LabIndicator{ Name="CHOLESTEROL", Description = "Cholesterol lvl"},
                new LabIndicator{ Name="HEMOGLOBIN", Description = "Hemoglobin lvl"},
                new LabIndicator{ Name="GLUCOSE", Description = "Glucose lvl"},
           }.ForEach(l => context.LabIndicators.Add(l));

           new List<LabValue>
           {
                new LabValue{ LabTestID = 1, LabIndicatorID = 1, Value = 2.3m },
                new LabValue{ LabTestID = 1, LabIndicatorID = 2, Value = 5.8m },
                new LabValue{ LabTestID = 1, LabIndicatorID = 3, Value = 5.2m },
                new LabValue{ LabTestID = 2, LabIndicatorID = 1, Value = 6.7m },
                new LabValue{ LabTestID = 2, LabIndicatorID = 2, Value = 9.8m },
                new LabValue{ LabTestID = 2, LabIndicatorID = 3, Value = 4.3m },
           }.ForEach(l => context.LabValue.Add(l));

           base.Seed(context);
     }
}

问题是,当我运行它时,EF尝试创建数据库时出现此错误:

INSERT语句与FOREIGN KEY约束“LabIndicator_LabValues”冲突。冲突发生在数据库“SummumnetDB”,表“dbo.LabIndicators”,列“ID”中。 该语句已终止。希望你能解决它,谢谢。

2 个答案:

答案 0 :(得分:0)

听起来好像你的模型绑定出了问题。你能为我们提供模型活页夹吗?如果你没有,你应该尝试创建一个。此外,您可以检查intellitrace插入语句实际执行的操作。

答案 1 :(得分:0)

插入订单的顺序是否错误?

从您的课程中可以看出LabIndicator有对现有LabValue记录的引用。

您是否尝试在最后两个类中恢复Seed中的顺序?

自:

new LabTest
new LabIndicator
new LabValue

new LabTest
new LabValue
new LabIndicator