Gra*_*ham 5 .net c# linq entity-framework
我在通过实体框架/Linq-to-Entities 访问数据库的存储库中有许多复杂的查询。这些查询通常由许多非平凡的子查询构成。一般来说,子查询用于不同的存储库方法以及其他域逻辑。它们位于存储库层的外部,但可以访问存储库层是有意义的。
因此,我想使用规范模式来封装其中一些子查询。
我正在为我的规范类使用基类:
public abstract class Specification<T> : ISpecification<T> where T : class
{
public abstract Expression<Func<T, bool>> ToExpression();
public virtual bool IsSatisfiedBy(T candidate)
{
var predicate = ToExpression().Compile();
return predicate(candidate);
}
public Specification<T> And(Specification<T> specification)
{
return new AndSpecification<T>(this, specification);
}
public Specification<T> Or(Specification<T> specification)
{
return new OrSpecification<T>(this, specification);
}
}
Run Code Online (Sandbox Code Playgroud)
示例规范可能如下所示:
public class IsAssignmentSetForStudentSpecification : Specification<Assignment>
{
private readonly Student _student;
public IsAssignmentSetForStudentSpecification(Student student)
{
_student = student;
}
public override Expression<Func<Assignment, bool>> ToExpression()
{
return x => !x.Exclusions.Contains(_student) &&
(
_student.Classes.Select(c => c.Subject).Intersect(x.Subjects).Any() ||
x.TutorGroups.Contains(_student.TutorGroup) ||
x.Houses.Contains(_student.House) ||
x.YearGroups.Contains(_student.YearGroup) ||
x.Students.Contains(_student)
);
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我不希望在每个存储库查询中都编写此类代码。
由于存储库查询方法(使用各种规范)可能如下所示:
public ICollection<Assignment> GetAssignmentsDueInForStudent(Student student, DateRange dateRange)
{
var isAssignmentAssignedToStudent = new IsAssignmentSetForStudentSpecification(student);
var isAssignmentDueInDateRange = new IsAssignmentDueInDateRangeSpecification(dateRange);
var hasStudentCompletedAssignment = new HasStudentCompletedAssignmentSpecification(student);
return (from a in Set
.Where(x => isAssignmentAssignedToStudent
.And(isAssignmentDueInDateRange).IsSatisfiedBy(x))
.Where(x => !hasStudentCompletedAssignment.IsSatisfiedBy(x))
select a)
.ToList(queryOptions);
}
Run Code Online (Sandbox Code Playgroud)
在上述方法中,Set是IDbSet<>
不幸的是,当我运行查询时,出现以下错误:
LINQ to Entities 无法识别方法 'Boolean IsSatisfiedBy(Beehive.Domain.Planner.Assignments.Assignment)' 方法,并且此方法无法转换为存储表达式。
我怎样才能解决这个问题?
小智 0
通过规范模式,您可以将域逻辑移出存储库。您可能有一个非常薄的存储库,如下所示:
public ICollection<Assignment> List(ISpecification<Assignment> specification)
{
return (from a in Set
.Where(specification.ToExpression())
select a)
.ToList(queryOptions);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在规范类中使用 And Or 和 Not 操作来组合规范,然后再传递它们。
var isAssignmentDueForStudent = new isAssignmentSetForStudentSpecification(student)
.And(new IsAssignmentDueInDateRangeSpecification(dateRange))
.And(new HasStudentCompletedAssignmentSpecification(student).Not());
return assignmentRepository.List(isAssignmentDueForStudent);
Run Code Online (Sandbox Code Playgroud)
这使得逻辑不存在于您的存储库中,并且数据层不依赖于您的规范实现。此外,当您实现 AndSpecifications 等时,您将覆盖ToExpression组合表达式,而不是IsSatisfiedBy可能不需要是虚拟的。
| 归档时间: |
|
| 查看次数: |
1437 次 |
| 最近记录: |