【发布时间】:2020-12-05 09:57:41
【问题描述】:
我在别处问过一个具体问题,但在没有回应和一些调查之后,我把它归结为更通用的东西,但我仍在努力构建表达式树。
我正在使用第三方库,它使用接口和扩展方法进行一些映射。这些映射被指定为一个表达式树,我想做的是从字符串值构建该表达式树。
扩展方法签名:
public static T UpdateGraph<T>(this DbContext context, T entity, Expression<Func<IUpdateConfiguration<T>, object>> mapping = null, bool allowDelete = true) where T : class, new();
接口IUpdateConfiguration只是一个标记接口,但有以下扩展方法:
public static class UpdateConfigurationExtensions
{
public static IUpdateConfiguration<T> OwnedCollection<T, T2>(this IUpdateConfiguration<T> config, Expression<Func<T, ICollection<T2>>> expression);
public static IUpdateConfiguration<T> OwnedCollection<T, T2>(this IUpdateConfiguration<T> config, Expression<Func<T, ICollection<T2>>> expression, Expression<Func<IUpdateConfiguration<T2>, object>> mapping);
public static IUpdateConfiguration<T> OwnedEntity<T, T2>(this IUpdateConfiguration<T> config, Expression<Func<T, T2>> expression);
public static IUpdateConfiguration<T> OwnedEntity<T, T2>(this IUpdateConfiguration<T> config, Expression<Func<T, T2>> expression, Expression<Func<IUpdateConfiguration<T2>, object>> mapping);
}
使用示例实体:
public class Person
{
public Car Car {get;set;}
public House House {get;set;}
}
所以正常的显式用法是:
dbContext.UpdateGraph(person, mapping => mapping.OwnedEntity(p => p.House).OwnedEntity(p=> p.Car));
我需要做的是从属性名称列表构建该映射,
var props = {"Car","House"}
dbContext.UpdateGraph(person, buildExpressionFromStrings<Person>(props);
到目前为止:
static Expression<Func<IUpdateConfiguration<t>, object>> buildExpressionFromStrings<t>(IEnumerable<string> props)
{
foreach (var s in props)
{
var single = buildExpressionFromString(s);
somehow add this to chaining overall expression
}
}
static Expression<Func<IUpdateConfiguration<t>, object>> buildExpressionFromString<t>(string prop)
{
var ownedChildParam = Expression.Parameter(typeof(t));
var ownedChildExpression = Expression.PropertyOrField(ownedChildParam, prop);
var ownedChildLam = Expression.Lambda(ownedChildExpression, ownedChildParam);
// Up to here I think we've built the (o => o.Car) part of map => map.OwnedEntity(o => o.Car)
// So now we need to build the map=>map.OwnedEntity(ownedChildLam) part, by calling Expression.Call I believe, but here I'm getting confused.
}
实际上,现实世界的代码比这更复杂(需要处理递归和子属性/映射),但我认为一旦我为一个级别构建了表达式,我就可以对其进行排序。一天多来,我一直在努力解决这个问题……为了提供一些上下文,我使用实体框架和一些配置来定义聚合根。
【问题讨论】:
标签: c# entity-framework linq expression-trees