My code-first database was working great. If I made a change to my database context the database would be updated the next time I started the application. But then I added some models to the database and got this error when I restarted my application:
Introducing FOREIGN KEY constraint 'FK_OrderDetails_Orders_OrderId' on table 'OrderDetails' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
One of the weird things is that if I start the application up again without changing anything, I then get this error:
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
To get the first error to happen again, I have to delete my .mdf and .ldf files (the database) and replace just the .mdf file with a copy from my revision history.
Why in the world is this happening?
For reference:
My Global.asax.cs file has this within the Application_Start()
method:
Database.SetInitializer<EfDbContext>(new EfDbContextInitializer());
Which looks like this:
public class EfDbContextInitializer : DropCreateDatabaseIfModelChanges<EfDbContext>
{
protected override void Seed(EfDbContext context)
{
var orders = new List<Order>
{
. . .
};
orders.ForEach(s => context.Orders.Add(s));
. . . etc. . .
context.SaveChanges();
}
}
My connection string from Web.config
:
<add name="EFDbContext" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;database=pos;AttachDBFilename=|DataDirectory|pos.mdf;MultipleActiveResultSets=true;User Instance=true" providerName="System.Data.SqlClient" />
And, finally, my Order and OrderDetails models (what the first error is directly referencing):
public class Order
{
public int OrderId { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
public int EstablishmentId { get; set; }
public virtual Establishment Establishment { get; set; }
}
public class OrderDetail
{
public int OrderDetailId { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
public virtual Product Product { get; set; }
public virtual Order Order { get; set; }
}
Update / Note: If I comment out public int OrderId { get; set; }
in my OrderDetail class, the project starts up fine (although I do not get the desired ability to add an OrderId
(of course).
See Question&Answers more detail:
os