Entity Framework Code First can generate the DB for the following POCOs.
public class Item {
public int Id { get; set; }
public string Name { get; set; }
}
public class ItemPair {
public int Id { get; set; }
public virtual Item FirstItem { get; set; }
public virtual Item SecondItem { get; set; }
}
I would like to establish the relationship with First and Second item via ID fields rather than the an entire "Item" class. So:
public class ItemPair {
public int Id { get; set; }
public virtual Item FirstItem { get; set; }
public int FirstItem_Id { get; set; }
public virtual Item SecondItem { get; set; }
public int SecondItem_Id { get; set; }
}
also works. Edit: This didn't actually work. Just generates additional FirstItem_Id1 and SecontItem_Id2 columns.
But just changing the foreign key properties to FirstItemId, SecondItemId, (without the underscore) like so:
public class ItemPair {
public int Id { get; set; }
public virtual Item FirstItem { get; set; }
public int FirstItemId { get; set; }
public virtual Item SecondItem { get; set; }
public int SecondItemId { get; set; }
}
results in the following exception.
{"Introducing FOREIGN KEY constraint 'ItemPair_SecondItem' on table 'ItemPair' may cause
cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION,
or modify other FOREIGN KEY constraints.\r\nCould not create constraint.
See previous errors."}
Why? And what can I do to avoid this exception.
I decided to just remove the cascade delete convention.
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}
The reasons are:
Thank you Ladislav Mrnka pointing me in the right direction.
My expectation is that in the first case your Id properties are not used in the database as FKs and EF will create another two columns (you can validate this by forcing pairing of navigation property with FK property using ForeignKeyAttribute
). In the second case EF will correctly recognize your properties but it will also use cascade delete convention which will cause error in SQL server. You have two properties from the table pointing to the same parent. Actually in the database you can createItemPair
from the same Item
(both FKs set to the same Id). If both relations have cascade delete enabled it will result in multiple cascade paths => not allowed in SQL server.
The solution here is fluent mapping to manually define how the relations are mapped. Here is the example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With