vendredi 24 novembre 2017

Build expression from object

I have the following object received from Angular client application in ASP.NET Core:

public class ModelFromClient
{
  public string name {get;set;}      //Database field is Name
  public int qunatity {get;set;}     //Database field is Quantity
}

And I have a EF Table class:

[Table("MyTable")]
public class MyRow
{
  public int Id {get;set;}  
  public string Name {get;set;}
  public int Qunatity {get;set;}
}

Now I need to create expression from ModelFromClient to Expression<Func<MyRow, MyRow>> and I need it with generic. Without generics solution would be:

public Expression<Func<MyRow, MyRow>> ToExpression(ModelFromClient Model)
{
    Expression<Func<MyRow, MyRow>> result = (t) => new MyRow()
    {
        Name = Model.name, 
        Quantity = Model.qunatity
    };
    return result;
}

But I would like something like that:

public Expression<Func<T, T>> ToExpression<T>(object Model) where T: new()
{
    Expression<Func<T, T>> result = (t) => new T();
    foreach(var prop in Model.GetType().GetProperties()) 
    {
       //compile error Fields does not exists.
       result.Body.Fields.Add(prop.Name.Capitalize(), prop.GetValue(Model, null));  //capitalize returns Name from input name
    }
    return result;
}

I need expression to pass it to Update extension method of EntityFramework-Plus.





Aucun commentaire:

Enregistrer un commentaire