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

entity-framework entity-framework-6 insert

Question

Sorry if this is repetitive; I'm having trouble locating the precise response to this query.

I have three tables set up as follows:

FirstName, LastName, PersonId

Business: CompanyId, BusinessName

Order: PersonId, OrderId, and CompanyId

My Order entity class, which was created by EF, includes navigation properties of type Person (not PersonId) and Company because the Order table has a foreign key declared on the columns PersonId and CompanyId.

I must thus first query the person and company tables to obtain the person and company entities before I can insert data into the Order table. The Order object can then be created and saved to the database using the Person and Company entities.

I am given a PersonId and a CompanyId in my scenario.

I would just perform INSERT INTO Order Set (CompanyId, PersonId) - 1 database call in traditional SQL. But with EF, I have to make three database calls. This seems excessive.

Is there a solution to this?

PS: I am utilizing EF 6. I am aware that I can create an expression and only have one call, but that would still result in two subselects.

1
3
3/27/2014 8:55:28 PM

Popular Answer

Foreign key properties can simply be added to the navigation properties and set using the existing ids. By doing this, you will avoid having to search the database for related items only to set the relationship.

2
3/27/2014 9:34:25 PM


Related Questions





Related

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