如何创建要在另一个表达式中使用的表达式?

时间:2011-03-11 17:13:06

标签: c# .net linq-to-sql expression expression-trees

我使用Linq2Sql来访问为此实现的DB和Repository模式。

public abstract class RepositoryBase<T, TDb> : IRepository<T>
{
    public IQueryable<T> GetAll()
    {
        return GetTable().Select(GetConverter());
    }
}

public class ProductRepository
    : RepositoryBase<IProduct, DbData.Product>
{
    protected override Table<DbData.Product> GetTable()
    {
        return Context.CustomerProducts;
    }

    protected override Expression<Func<DbData.Product, IProduct>> GetConverter()
    {
        return dbEntity =>
             (ProdType.ProdTypeEnum)dbEntity.ProdId==ProdType.ProdTypeEnum.MyType
                    ? (new Product1{...}) as IProduct
                    : (new Product2{...}) as IProduct
    }
}

我需要以这种方式修改提到的代码:

    protected override Expression<Func<DbData.Product, IProduct>> GetConverter()
    {
        return dbEntity => 
             (ProdType.ProdTypeEnum)dbEntity.ProdId==ProdType.ProdTypeEnum.MyType
             || (ProdType.ProdTypeEnum)dbEntity.ProdId==ProdType.ProdTypeEnum.My2ndType
             || (ProdType.ProdTypeEnum)dbEntity.ProdId==ProdType.ProdTypeEnum.My3rdType
                    ? (new Product1{...}) as IProduct
                    : (new Product2{...}) as IProduct
    }

因为我会在其他地方进行同样的检查,我想分开一个功能:

public static bool IsProductOfType1(ProdType.ProdTypeEnum eProdTypeId)
{
    return eProdTypeIdd==ProdType.ProdTypeEnum.MyType
             || eProdTypeId==ProdType.ProdTypeEnum.My2ndType
             || eProdTypeId==ProdType.ProdTypeEnum.My3rdType
}


    protected override Expression<Func<DbData.Product, IProduct>> GetConverter()
    {
        return dbEntity => 
             IsProductOfType1((ProdType.ProdTypeEnum)dbEntity.ProdId)
                    ? (new Product1{...}) as IProduct
                    : (new Product2{...}) as IProduct
    }

以下情况引发异常:

  

方法'Boolean IsProductOfType1(Int32)'没有支持的SQL转换

似乎在'GetConverter'方法中我不需要使用方法,而是使用表达式。但我不知道那是什么语法。

请指教。非常感谢!

1 个答案:

答案 0 :(得分:0)

问题在于:

public static bool IsProductOfType1(ProdType.ProdTypeEnum eProdTypeId)

此方法应返回Expression<T>而不是bool。任何对外部方法的调用都不会被LINQ to SQL

转换