Search code examples
sql-serverasp.net-mvcentity-frameworkforeign-key-relationship

Adding 2 linked EntityFramework objects doesn't link


I have two entities in my EntityFramework 6.1.1 model that are linked by a foreign key in the backing SQL database. I have a Location entity which contains address details and I have a Client entity which contains name details and a nullable foreign key ID for a Location.

I'm building my first MVC site but have utilised EntityFramework for over 6 years and have been building Microsoft systems for over 10 years. The behaviour below makes no sense to me...

The following code in my Create method SHOULD work:

Location location = new Location { LocationID = cvm.Location.LocationID, LocationTypeID = cvm.Location.LocationTypeID, LocationData = string.Empty };
db.Locations.Add(location);
Client client = new Client { ClientID = cvm.ClientID, ClientTypeID = cvm.ClientTypeID, Email = cvm.Email, PhoneNumber = cvm.PhoneNumber, ESign = cvm.ESign, ClientData = string.Empty };
db.Clients.Add(client);
client.Location = location;
db.SaveChanges();

Unfortunately the result after the SaveChanges is called is that both of the entities are inserted into their respective database tables BUT the foreign key in the Client table is null! I've tried manually setting the LocationID property in the Client entity but it makes no change. I've tried saving the Location entity BEFORE adding the Client entity but it makes no change. The ONLY way I can get the link to work is with the following code:

Location location = new Location { LocationID = cvm.Location.LocationID, LocationTypeID = cvm.Location.LocationTypeID, LocationData = string.Empty };
db.Locations.Add(location);
Client client = new Client { ClientID = cvm.ClientID, ClientTypeID = cvm.ClientTypeID, Email = cvm.Email, PhoneNumber = cvm.PhoneNumber, ESign = cvm.ESign, ClientData = string.Empty };
db.Clients.Add(client);
db.SaveChanges();
client.Location = location;
db.Entry(client).State = EntityState.Modified;
db.SaveChanges();

The most frustrating part is that I have another entity (Property) which also has a foreign key link to the Location entity. In the Property table however the LocationID foreign key is NOT nullable, and the (equivalent) first code DOES work.

Has anyone else run into this issue and can explain why the first code isn't working? Is it possible this is an EF6.1.1 bug?


Solution

  • You don't have to explicitly save the child(location)

    Location location = new Location { LocationID = cvm.Location.LocationID, LocationTypeID = cvm.Location.LocationTypeID, LocationData = string.Empty };
    Client client = new Client { ClientID = cvm.ClientID, ClientTypeID = cvm.ClientTypeID, Email = cvm.Email, PhoneNumber = cvm.PhoneNumber, ESign = cvm.ESign, ClientData = string.Empty };
    client.Location = location;
    db.Clients.Add(client);
    db.SaveChanges();