Kim*_*jan 5 c# linq specification-pattern entity-framework-4
我偶然发现在LINQ查询中使用我的规范.麻烦在于我的规范与params.
让我们假设一个简单的场景:
public class Car {
public Guid Id { get; set; }
public string Color { get; set; }
public int UsedPieces { get; set; }
// whatever properties
}
public class Piece {
public Guid Id { get; set; }
public string Color { get; set; }
// whatever properties
}
public static class PieceSpecifications : ISpecification<Piece> {
public static ISpecification<Piece> WithColor(string color) {
return new Specification<Piece>(p => p.Color == color);
}
}
Run Code Online (Sandbox Code Playgroud)
我真正想做的事情
// Get accepts ISpecification and returns IQueryable<Car> to force just one call to database
var carWithPieces = _carRepository.Get(CarSpecifications.UsedPiecesGreaterThan(10));
var piecesWithColor = from p in _pieceRepository.Get()
let car = carWithPieces.FirstOrDefault() // entire query will does one call to database
where PieceSpecifications.WithColor(car.Color).IsSatisfiedBy(p) // unfortunately it isn't possible
// where p.Color == car.Color -> it works, but it's not what I want
select p;
Run Code Online (Sandbox Code Playgroud)
我知道这有点令人困惑,但我试图避免在我的真实(大)场景中进行大量的往返,我知道实际上使用原始LINQ和实体框架是不可能的.我厌倦了尝试这么多博客和失败(我的)方法.有人知道一些真正好的方法.还有另一种方法吗?
错误
System.NotSupportedException:LINQ to Entities无法识别方法'Boolean IsSatisfiedBy(App.Model.Piece)'方法,并且此方法无法转换为商店表达式.
UPDATE
基本规格模式
public class Specification<T> : ISpecification<T> {
private readonly Expression<Func<T, bool>> _predicate;
public Specification(Expression<Func<T, bool>> predicate) {
_predicate = predicate;
}
public Expression<Func<T, bool>> Predicate {
get { return _predicate; }
}
public bool IsSatisfiedBy(T entity) {
return _predicate.Compile().Invoke(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
如果我这样做,它很容易整洁
// call to database
var car = _carRepository
.Get(CarSpecifications.UsedPiecesGreaterThan(10))
.FirstOrDefault();
// Whoah! look I'm working, but calling to database again.
var piecesWithColor = _pieceRepository
.Get(PieceSpecifications.WithColor(car.Color))
.ToArray();
Run Code Online (Sandbox Code Playgroud)
知识库
// The Get function inside repository accepts ISpecification<T>.
public IQueryable<T> Get(ISpecification<T> specification) {
return Set.Where(specification.Predicate);
}
Run Code Online (Sandbox Code Playgroud)
如果要在 LINQ 到实体查询中使用表达式,则无法编译和调用它。尝试直接使用Predicate
,因为 LINQ-to-entities 构建由 EF LINQ 提供程序评估并转换为 SQL 的表达式树。
恕我直言,以这种方式使用规范是没有意义的。LINQ 到实体查询是一个复合规范。因此,要么使用 Linq-to-entities,要么使用规范构建您自己的查询语言,并让您的存储库将您的查询转换为 LINQ 查询。
归档时间: |
|
查看次数: |
2134 次 |
最近记录: |