Entity Framework Code First: How can I model a Customer / Address relationship?
Here is my simplified model:
public class Customer
{
public int ID { get; set; }
public int MailingAddressID { get; set; }
[ForeignKey("MailingAddressID")]
public Address MailingAddress { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Address
{
public int ID { get; set; }
public int CustomerID { get; set; }
[ForeignKey("CustomerID")]
public Customer Customer { get; set; }
}
When I try and create the database I get the following error:
开发者_StackOverflowIntroducing FOREIGN KEY constraint 'Customer_MailingAddress' on table 'Customers' 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.
I don't understand what the problem is. I understand that a Customer with an Address cannot be deleted and also that an Address which is a Customer's Mailing Address can also not be deleted.
This fits with my design because if a Customer has one or more addresses, then one must be a mailing address and that address can not be deleted.
So what am I missing here? Thanks!
Edit:
Forgot to mention that I tried adding the following line in the OnModelBuilding method:
modelBuilder.Entity<Customer>().Property(x => x.MailingAddressID).IsOptional();
This allows the database to be built, however when adding a customer I get the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint "Customer_MailingAddress". The conflict occurred in database "DomainModel.SeasideHeightsEntities", table "dbo.Addresses", column 'ID'. The statement has been terminated.
Still at a loss as to how to model this properly.
The problem is... which gets deleted first, the customer, or the mailing address? You can't delete them both at the same time, the deletes will happen in a sequence. When the first gets deleted, it fails the rule b/c the second hasn't been deleted yet.
From what I can see of your model, I'd not use the foreign keys to handle this logic, I'd handle it during object validation by putting a [Required] attribute on the MailingAddress property instead of the foreignkey.
You should also consider additional implementation logic to ensure that the MailingAddress is part of the Addresses collection.
精彩评论