How can I create expression to be used in another expression?
I use Linq2Sql to access DB and Repository pattern implemented for that.
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
}
}
I need to modify mentioned code in this way:
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
}
As I will have same check in other places I would like to separate a function:
public stati开发者_JS百科c 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
}
The following case throws an exception:
Method 'Boolean IsProductOfType1(Int32)' has no supported translation to SQL
It seems like inside of 'GetConverter' method I need to use not a method, but an expression. But I don't know what is syntax of that.
Please advise. Thanks a lot!
The problem lies here:
public static bool IsProductOfType1(ProdType.ProdTypeEnum eProdTypeId)
This method should return an Expression<T>
instead of bool
. Any call to external methods won't be converter by LINQ to SQL
精彩评论