繁体   English   中英

实体框架核心 - 使用接口作为参数的表达式树

[英]Entity Framework Core- Use Expression Tree With Interface As Parameter

我将非常感谢以下场景的一些帮助。 我有以下课程:

public class Product : IHasPrice
{
    public string Title { get; set; }
    public int Price { get; set; }
    public string CustomerId { get; set; }

}

public interface IHasPrice
{
    int Price { get; set; }
}

public class ProductProvider
{
    public ProductProvider()
    {
    }

    public IEnumerable<Product> GetByCustomer(string customerId, Expression<Func<IHasPrice, bool>> predicate = null)
    {
        using (var db = new ApplicationDbContext())
        {
            var queryable = db.Products.Where(p => p.CustomerId == customerId);
            if (predicate != null)
            {
                return queryable.Where(predicate).ToList();
            }
            else
            {
                return queryable.ToList();
            }
        }
    }
}

我希望能够以一种只能按客户选择的方式使用ProductProvider ,但您也可以按您喜欢的任何方式(并且仅按价格)过滤价格。 此示例不起作用,因为queryable.Where需要 typeof Expression(Func(Product, bool)) 有没有办法做到这一点,或者我必须在过滤价格之前将数据提取到内存中?

由于IQueryable<out T>接口是协变的,传递的 lambda 表达式可以直接与Where方法一起使用:

var query = queryable.Where(predicate);

唯一的问题是现在结果查询的类型是IQueryable<IHasPrice> 您可以使用Queryable.Cast方法将其转回IQueryable<Product>

var query = db.Products.Where(p => p.CustomerId == customerId);
if (predicate != null)
    query = query.Where(predicate).Cast<Product>(); // <--
return query.ToList();

已测试并使用最新的 EF Core 2.2(在某些早期版本中可能会失败)。


另一种解决方案是通过“调用”将Expression<Func<IHasPrice, bool>>转换为预期的Expression<Func<Product, bool>>

var query = db.Products.Where(p => p.CustomerId == customerId);
if (predicate != null)
{
    var parameter = Expression.Parameter(typeof(Product), "p");
    var body = Expression.Invoke(predicate, parameter);
    var newPredicate = Expression.Lambda<Func<Product, bool>>(body, parameter);
    query = query.Where(newPredicate);
}
return query.ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM