I am trying to create a generic "update expression builder" - an object that can be passed around, and used to indicate which fields need to be assigned what value. What I did is :
public class UpdateExpression<TClass> : Dictionary<Expression<Func<TClass, object>>, object>
{};
public class UpdateExpressionBuilder<TClass>
{
private UpdateExpression<TClass> fieldsValues;
public UpdateExpressionBuilder()
{
fieldsValues = new UpdateExpression<TClass>();
}
public UpdateExpressionBuilder<TClass> Add<TField>(Expression<Func<TClass, TField>> field, TField value)
{
fieldsValues.Add(field, value);
return this;
}
public UpdateExpression<TClass> Build()
{
return fieldsValues;
}
}
Which is meant to be used as:
var personUpdateExpression = new UpdateExpressionBuilder<Person>()
.Add(p => p.FirstName, "David")
.Add(p => p.MiddleName, "A")
.Build();
And then I can send personUpdateExpression as a parameter to any method, for example a database update.
The problem is that the call fieldsValues.Add(field, value)
does not compile. Error is:
error CS1503: Argument 1: cannot convert from
'System.Linq.Expressions.Expression<System.Func<TClass, TField>>' to
'System.Linq.Expressions.Expression<System.Func<TClass, object>>'
I tried adding constraints where TField : class, new()
but this did not change anything.
When changing the signature of Add to
Add(Expression<Func<TClass, object>> field, object value)
It works perfectly. However then I loose the compile time type checking, so that Add(p => p.FirstName, 123)
will compile, but fail on runtime.