My first database worked fine. If I made changes to my database context, the database would be updated the next time the application was launched. But then I added some models to the database and got this error when restarting the 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 run the application again without changing anything, I get the following 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.
In order for the first error to happen again, I must delete my .mdf and .ldf files (database) and replace only the .mdf file with a copy from my change history.
Why is this happening in the world?
For reference:
My Global.asax.cs file has this value in 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 is 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 (that the first error is directly referenced):
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 on public int OrderId { get; set; } public int OrderId { get; set; } public int OrderId { get; set; } in my OrderDetail class, the project will start working fine (although I don't get the desired ability to add OrderId (of course).