Entity Framework (4.0) - Adding new records with Foreign Key
We have a table "Issues" with a foreign fey to the "Contacts" table". Ideally when a new Issue is added the user should select the Contact from a drop down. However, in some cases the contact may not already exist, so the user can add minimal new contact details to get the issue into the database. (This is a Support Desk app, and speed is of the essence to the operators). The contact 开发者_开发技巧data is cleaned up at a later date.
So in the code we detect a new contact and create a new one in the database using Entity Framework: _context.AddToContacts(_contact);
. We then need to retrieve the new id for updating on the issue - so a read from the contacts table to get last record added.
This works fine.
Then we build the Issues record, including the new foreign key using ContactsReference.EntityKey
.
When we Save the Issue SaveChanges
we get the Issue record okay (with the correct foreign key back to Contacts) but we get another Contacts record added to the database.
Are we doing too much work here? Or should Entity Framework be able to handle both adds and manage the data link correctly between the tables?
You can do both of these in a single transaction.
var contact = new Contact(){/*initialize properties*/};
var issue = new Issue(){/*initialize properties*/};
issue.Contact = contact;
_context.AddToIssues(issue);
_context.SaveChanges();
EF will detect the new Contact and will add it.
精彩评论