I have the following method:
public void Update<T>(T entity, IEnumerable<Expression<Func<T, Object>>> properties)
where T : class
{
_context.Set<T>().Attach(entity);
foreach (var property in properties)
_context.Entry<T>(entity)
.Property(((MemberExpression)property.Body).Member.Name)
.IsModified = true;
} // Update
I am passing an Entity Framework entity, attaching it and Set each property as modified.
I would like to use it as follows:
_repository.Update<File>(file, new { x => x.Data, x => x.Name });
So I am passing a file and saying the Data and Name properties were modified.
But I am getting the error:
The best overloaded method match for 'Update<File>(File,
IEnumerable<System.Linq.Expressions.Expression<System.Func<File,Object>>>)'
has some invalid arguments
How should I change my method to be able to use it as I mentioned?
Or maybe:
_repository.Update<File>(file, x => x.Data, x => x.Name);
Or even:
_repository.Update<File>(file, x => new { x.Data, x.Name });
It looks like you really want:
public void Update<T>(T entity, params Expression<Func<T, Object>>[] properties)
where T : class
and then call it as:
_repository.Update(file, x => x.Data, x => x.Name);
(Note that I'm using type inference here rather than explicitly using _repository.Update<File>(...)
.)
The params
part is how you can specify multiple arguments to be converted into an array. There's no need for an anonymous type at all. if you really wanted an anonymous type, you could access its members by reflection - but that would be pretty ugly and I suspect you'd need to cast each lambda expression too (as otherwise the compiler wouldn't be able to infer its type).
See more on this question at Stackoverflow