Saturday, August 18, 2018

Is there a way to coax Entity Framework into finding a foreign key during an insert?

I often have a situation where I have an aggregate with a reference to some other entity using a domain specific ID. When I then save the aggregate via the repository using Entity Framework, I need to get the database id of the referenced entity instead of the domain id.

For example, say I have these classes in my domain (notice the lack of any database ID):

MyDomainEntity

  • MyDomainEntityID
  • SomeProperty
  • IsoLanguageCode (Foreign Domain Identifier)

Language

  • IsoLanguageCode (Domain Identifier)
  • Name

In Entity Framework Code First, my entity classes to persist my domain would look something like this:

MyDomainEntity

  • DbId (Primary Key)
  • MyDomainID
  • SomeProperty
  • LanguageId (Database Foreign Key)

LanguageEntity

  • DbId
  • IsoLanguageCode
  • Name

In order to save an instance of MyDomainEntity, I need to make an extra call to the database to retrieve the database id of the language. This results in two calls to the database. If I was working with pure SQL, I could construct an insert statement to set the LanguageId based on a IsoLanguageCode value, completing the insert in one statement.

My question is, is it possible to coax Entity Framework to discover and assign the foreign key database id in one call? Or do I always have to retrieve the LanguageEntity first, in order to construct MyDomainEntity.

Solved

Entity framework can only do this if you also expose the foreign keys, your database generated values.


No comments:

Post a Comment