I'm having some troubles when trying to set my DB using a Initializer. I've 3 tables, LabTest->LabValue<-LabIndicator, and this is how I code it:
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; }
}
This is how i coded my Db Intializer in my DBContext:
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);
}
}
The thing is, when I run it, and EF tries to create the database i get this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "LabIndicator_LabValues". The conflict occurred in database "SummumnetDB", table "dbo.LabIndicators", column 'ID'. The statement has been terminated. Hope you can work it out, thanks.
It awfully sounds like something is going wrong with your model binding. Could you provide us with the model binder? If you don't have it, you should try creating one. In addition, you could check the intellitrace what the insert statement is actually doing.
Is the order from your inserts in wrong order?
It looks from your classes that a LabIndicator
has a reference to an existing LabValue
record.
Have you tried reverting the order in Seed
for last two classes?
From:
new LabTest
new LabIndicator
new LabValue
To
new LabTest
new LabValue
new LabIndicator
精彩评论