Update entity from expression (EF Core 2.0)

entity-framework entity-framework-core


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 T is entity.
I have loaded entity from database using Where and Single.

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.


//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 DbUser after 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.

12/18/2017 8:26:23 AM

Popular Answer

the magic line you are looking for:

var resultOfTypeT = expr.Compile().Invoke(entity)

But then entity needs to be an instance of type T , not DbUser 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.

But the 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.

Now your 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.

12/18/2017 9:02:36 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow