I do not understand what EF says about "non-public foreign keys" in the exception. I would consider internal exception as an important part:
It is not possible to determine the actual ordering for dependent operations. dependencies may exist due to foreign key constraints, model requirements, or store values.
I think the problem in your model is that you have a mutual relationship between Customer and Address : the client needs the address (you marked it as mandatory in your cartographic code) and, on the other hand, the client needs the address (the default is ) due to a non-elementary foreign key and because of your mapping code). So, EF does not know which object to save first in your code example - default address or client? Both objects need the primary key of the other, which must be stored with valid FK restrictions.
The simplest solution that I see is to make an optional default address in your model and then save twice (I omit the mappings that work by convention anyway):
public class Customer { private ICollection<Address> m_Addresses; public Customer() { Addresses = new List<Address>(); } public int Id { get; set; } public string CompanyName { get; set; } public virtual ICollection<Address> Addresses { get { ... } set { ... } } public Address DefaultAddress { get; set; } public int? DefaultAddressId { get; set; }
And then your program will look like this:
static void Main(string[] args) { Customer headOffice = new Customer(); headOffice.CompanyName = "C1"; Address address = new Address(); address.Town = "Colchester"; headOffice.Addresses.Add(address); address = new Address(); address.Town = "Norwich"; headOffice.Addresses.Add(address);
This double SaveChanges is ugly, but I see no other way.
source share