【发布时间】:2018-05-08 04:42:13
【问题描述】:
我从 ASP.NET Core 中的 Angular 客户端应用程序收到以下对象:
public class ModelFromClient
{
public string name {get;set;} //Database field is Name
public int qunatity {get;set;} //Database field is Quantity
}
我有一个 EF Table 类:
[Table("MyTable")]
public class MyRow
{
public int Id {get;set;}
public string Name {get;set;}
public int Qunatity {get;set;}
}
现在我需要创建从ModelFromClient 到Expression<Func<MyRow, MyRow>> 的表达式,并且我需要它的泛型。
没有泛型的解决方案是:
public Expression<Func<MyRow, MyRow>> ToExpression(ModelFromClient Model)
{
Expression<Func<MyRow, MyRow>> result = (t) => new MyRow()
{
Name = Model.name,
Quantity = Model.qunatity
};
return result;
}
但我想要这样的东西:
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;
}
我需要表达式将其传递给 EntityFramework-Plus 的 Update 扩展方法。
【问题讨论】:
-
请在答案中发布您的解决方案,而不是作为对问题的编辑以了解更多信息,请参阅tour
-
如果您觉得现有答案不够充分,需要发布您自己的答案,请发布解决方案作为答案,而不是作为对题。问题是您在哪里提出问题,而不是您在哪里发布解决方案。
标签: c# reflection expression entity-framework-plus