通过反思

时间:2016-11-22 11:30:26

标签: c# entity-framework generics reflection

我用Expression调用方法,它返回表中的最后一条记录:

   public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null)
{
    return specification == null
        ? Set().LastOrDefault()
        : Set().OrderBy(specification).LastOrDefault();
}

通过反思

 var methodCreateReadRepositoryAttr = (entityMetadata.GetEntityAttributeType() != null) ? 
typeof(IRepositoryFactory).GetMethod("CreateReadRepository").MakeGenericMethod(entityMetadata.GetEntityAttributeType()) : null;

    var methodEntityGet3 = attributeReadRepository.GetType().GetMethod("FindLast");
var closedGenericMethod = methodEntity3.MakeGenericMethod(new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) };

Expression <Func<ArticleAttribute, int>> articleReturnExpression = e => e.ArticleAttributeID;   

 var fromRepo3 = closedGenericMethod.Invoke(attributeReadRepository, new object[] {articleReturnExpression});

在最后一行我有错误消息

  

类型'System.Linq.Expressions.Expression 1[System.Func 2 [RRP.Framework.Domain.Entities.ArticleAttribute,System.Int32]]'的对象无法转换为'System.Linq.Expressions.Expression类型1[System.Func 2 [RRP.Framework.Domain.Entities.ArticleAttribute,System.Linq.Expressions.Expression 1[System.Func 2 [RRP.Framework.Domain.Entities.ArticleAttribute,System.Int32]]]]”。

1 个答案:

答案 0 :(得分:1)

您正在将通用参数类型与方法参数类型混合。

您方法的唯一通用参数

public T FindLast<TKey>(Expression<Func<T,TKey>> specification = null)

TKey。因此

var closedGenericMethod = methodEntity3.MakeGenericMethod(
    new Type[] { typeof(Expression<Func<ArticleAttribute,int>>) });

应该是

var closedGenericMethod = methodEntity3.MakeGenericMethod(
    new Type[] { typeof(int) });