How can I update entity from expression?
I dynamically build which properties(columns) should be updated. Function that do that returns
Expression<Func<T, T>> where
I have loaded entity from database using
Expression<Func<T, T>> expr = this.CallVirtualMethodAndGetExpression(ModelFromRequest); DbUser entity = this.context.Users.Where(t => t.Id == 1).Single(); some magic ??? //tried expr.Compile()(entity) but it does not work. this.context.SaveChanges(); //use DbUser with updated properties of course.
I know I could use EF Plus (batch update), but I want to stick with
SaveChanges (I need
SaveChanges and I want to avoid sending another request).
I have entity object and expression. Now, I need to edit entity object based on expression and called
SaveChanges which should update entity.
the magic line you are looking for:
var resultOfTypeT = expr.Compile().Invoke(entity)
entity needs to be an instance of type
T , not
So this does not make sense to me.
So i cant give you exact code to compile for you, since i cant see the method signature where
T is defined. and also do not know what the method signature of
this.CallVirtualMethodAndGetExpression(ModelFromRequest) looks like.
Compile() will change the
Expression<Func<T,T>> to just
Func<T,T> which can then
Invoke the defined functionality for
Func<T,T> if you have a valid instance of
T to pass to it.
entity is not of type
T, since it is of type
DbUser So you are probably going to need to change your Method Signature or get your DbUser in a generic way or something. If you are only going to need to pass a
DbUser instance, you do not need c# Generics. but cant really tell with just the current information available.