I’m not sure if this is possible but I am inserting a lot of entities into the database, and for each item it has say a language property which is an entity. Currently I create a new language object for each item that is being inserted but this is just for testing as it creates a lot of duplicates. The languages should be unique in the database and should just point to an existing language record, the only way I can think of is to do seperate service calls for every insert to lookup a language code and get the id of the existing language which is a lot of overhead.
Is there a way for it to automatically lookup a record based on the language code and use that record?
Thanks
Both
ObjectContextandDbContexthave methods that try to find an already loaded entity from the context in memory –GetObjectByKeyforObjectContextandFindforDbContext. Using these methods you avoid to load aLanguageentity more than once from the database.Both methods need a primary key value as input parameter to lookup the entity by key. Essentially think of these methods as accessing an internal dictionary that relates the primary key to the entity object.
Now, refering to your comment…
…you can’t use these methods because they rely on knowing the primary key value you want to lookup.
What I would do is to mimic the logic of the mentioned internal dictionary by your own dictionary that relates your “custom value” to the entity instead of the primary key. I assume that the custom value is unique in the
Languagetable.So, the idea would be:
Given you have entities like this…
…and you have a collection of data you are using to insert the new entities…
…then you could use this:
This would load only one
Languageentity perLanguageCustomValue, do this only once and doesn’t create duplicates ofLanguageobjects in the database.