Extension method to add LoadByKey to EntityFrameworks context
In previous post I left to the reader the task to build a LoadByKey extension method to make it easy loading entities by key in project with entity framework, I think that is quite interesting to spent a little bit on in. First of all I suggest you to read this post about metadata and Entity Framework, this post suggested me this solution.
|
|
In line 3 I begin a query to load the EntityType object related to the type of object I need to load. The System.Data.Metadata.Edm namespace is a place where you can find plenty of information about how your data is structured. I simply query the MetadataWorkspace getting the items of type DataSpace.CSpace or the Conceptual Model. The Conceptual model can be tricky to use, to familiarize with it I suggest you to use LINQPad to run the query of line 3, you get this result (all properties collapsed)
Now you can simply suppose that KeyMembers property of an entityType contains all the KeyProperties, if you expand it you will see this result
YATTA! This permits me to find name/s of key properties and I can use LINQ to create desidered EntityKey (line 8-11)
|
|
Ok, this code could be made more efficient avoiding the call to GetType and Metadata for each call, you can use static variables or you can use cache to store the list of KeyProperty for each object in a dictionary or similar structure. Now you can use this code to load entities knowing their keys
|
|
It works for entities with single property key as well as entities like Order_Details that have multiple keys; in this scenario you should pay a lot of attention to the order in witch the keys are declared to avoid confusion.
alk.