动态制作通用表达式时出错

时间:2016-11-05 13:59:20

标签: c# entity-framework generics lambda entity-framework-6

基于Generic expression abstraction issue我想制作一个更通用的方法来使用" UpdateGraph"使用实体框架6。

目前,我可以调用SetOwnedCollectionMapping(t => t.ClassProperty),但我希望通过使用类实例和任何类属性来创建一个更可重用的方法。

以下是我使用的示例:

private static void AddOrUpdate<T>(TDataEntity class1, T NavigationProperty) where T : class
{
    PropertyInfo pinfo = typeof(TDataEntity).GetProperty("PropertyName");
    object value = pinfo.GetValue(class1, null);

    ParameterExpression pe = Expression.Parameter(value.GetType(), "L");

    var arg = Expression.Constant(null, typeof(TDataEntity));
    var body = Expression.PropertyOrField(arg, "PropertyName");

    var lambda = Expression.Lambda(body);
    SetOwnedCollectionMapping(lambda);

    using (var db = new ConsoleContext())//
    {
        db.UpdateGraph(class1, graphMapping);
        db.SaveChanges();
    }
}

protected static Expression<Func<IUpdateConfiguration<TDataEntity>, object>> graphMapping { get; set; }

protected void SetOwnedCollectionMapping<T>(Expression<Func<TDataEntity, ICollection<T>>> mapping)
{
    Expression<Func<IUpdateConfiguration<TDataEntity>, object>> template = 
        _ => _.OwnedCollection(mapping);

    var map = Expression.Parameter(
        typeof(IUpdateConfiguration<TDataEntity>),
        "map");

    graphMapping = Expression.Lambda<Func<IUpdateConfiguration<TDataEntity>, object>>(
        Expression.Call(
            ((MethodCallExpression)template.Body).Method,
            map,
            Expression.Quote(mapping)),
        map);
}

我遇到的错误是调用方法SetOwnedCollectionMapping(lambda);

  

错误1方法的类型参数   &#39; ConsoleApplication1.Program.SetOwnedCollectionMapping(System.Linq.Expressions.Expression&GT;&GT;)&#39;   无法从使用中推断出来。尝试指定类型参数   明确。

我怀疑我的lambda表达方式。有人能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

看起来在AddOrUpdate你需要更新以下行以使编译器知道你将通过哪种类型

SetOwnedCollectionMapping<T>(lambda);