Reputation: 7448
I'll try to be as clear as possible:
My goal: to read the model configuration I declared in my overridden OnModelCreating
inside my Entity class derived from DbContext
.
Reason: To build a generic void Update<T>(T toUpdate)
method on my data layer, where I get which fields are the primary key for T, retrieve them on the passed toUpdate
object and use them in the Set<T>().Find
method.
This would allow me to not hard-code Find logic for every type of entity I handle.
I need to retrieve the stored entity to apply updates, like this:
var retrievedItem = _entities.Set<T>().Find(myRetrievedKeyValues);
_entities.Entry(retrievedItem).CurrentValues.SetValues(toUpdate);
I'm stuck at the point that in my _entities
instance (which is my entities class derived from DbContext
of course) I can't seem to find where the model configuration is stored.
Anyone can point me in the right direction?
Thanks.
Upvotes: 0
Views: 387
Reputation: 177133
You can find the code how to retrieve the key property names of an entity type YourEntity
here:
Entity Framework code first. Find primary key
And then retrieve the values:
public Update<T>(T toUpdate)
{
// Code from link above with YourEntity = T
List<object> myRetrievedKeyValues = new List<object>();
foreach (var keyName in keyNames)
myRetrievedKeyValues.Add(toUpdate.GetType().GetProperty(keyName)
.GetValue(toUpdate, null));
var retrievedItem = _entities.Set<T>().Find(myRetrievedKeyValues.ToArray());
_entities.Entry(retrievedItem).CurrentValues.SetValues(toUpdate);
}
Expect that you'll have a quite slow Update
method because you must use reflection for this generic approach.
Also don't forget that CurrentValues.SetValues
will only update scalar and complex properties. It does not help you to update navigation properties. You will have to use non-generic code to update the relationships which are specific to each entity type.
Upvotes: 1