Entity Framework - How to Insert to table with foreign keys without retrieving foreign table rows first

entity-framework entity-framework-6 insert


I'm having a hard time finding the exact answer to this question, so my apologies if this is redundant.

So I have 3 tables defined such that:

Person :PersonId, FirstName, LastName

Company: CompanyId, CompanyName

Order: OrderId, PersonId, CompanyId

On the Order table, there is a foreign key defined on the PersonId and CompanyId columns, thus, my Order entity class generated by EF has a navigation properties of type Person (not PersonId) and Company.

So, to insert into the Order table, I first need to query the person and company tables to get the person and company entities. Then I can construct the Order object using the Person and Company entities and save it to the db.

In my scenario, I am being passed a PersonId and CompanyId.

In classic SQL I would just do INSERT INTO Order Set (CompanyId, PersonId) - 1 database call. But with EF, I have to do 3 db calls. This seems like overkill.

Is there any way around this?

PS - I'm using EF 6. I know I could generate an expression and make it single call..but that would still yield two subselects.

3/27/2014 8:55:28 PM

Popular Answer

You can just include foreign key properties in addition to the navigation properties and then set them using the ids you have. If you do this will not have to go to the database to get related entities for just a sake of setting the relationship.

3/27/2014 9:34:25 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow