我正在尝试通过传递需要加载的子对象表达式来在存储库中实现一种急切加载功能。
Candidate Get(int candidateId, params Expression<Func<Candidate, object>>[] includes);
那么我的服务可以像这样调用:
candidateRepository.Get(1, p => p.Notes, p => p.Profile, p => p.Application);
“笔记”、“个人资料”和“应聘申请”都是“候选人”属性的一部分。例如:
public class Candidate
{
public string Name { get; set; }
public IList<CandidateNote> Notes { get; set; }
public Profile Profile { get; set; }
public Application Application { get; set; }
}
所以,在存储库内,我需要确定是否传递了属性到表达式参数中以实际尝试水合化它。但是我没有看到一种优雅的方式来实现这一点。
public Candidate Get(int candidateId, params Func<Candidate, object>[] includes)
{
...
if (candidate.Notes property was specified?)
{
candidate.Notes = this.candidateNoteRepository.List(candidateId);
}
return candidate;
}
似乎我可以通过表达式 (includes[0].Body as MemberExpression).Member.Name
获取属性名称,但是似乎应该有更简单的方法。而且我不喜欢字符串比较。除非没有其他办法,否则我真的不想这样做:
if (includes[0].Body as MemberExpression).Member.Name == "Notes")
{
似乎这应该是非常简单的东西,例如:
if (includes[0].Is(candidate.Notes) or includes[0](candidate.Notes).Match())
{
如果出现这种情况,我非常希望将includes保留为Expression数组,因为尽管我今天正在使用ADO.NET,但我们计划最终采用Entity Framework,并且这些表达式将非常适用于Include方法。
return this.Filter(m => m.Candidates.CandiateId == candidateId)
.Include(includes[0])
MemberExpression
表达式中的MemberInfo
对象获取/填充属性,而不是尝试为所有属性硬编码所有这些if
语句。 - Servy