Entityframework双向依赖项预查询

时间:2015-01-13 15:16:43

标签: c# .net linq entity-framework entity-framework-6

我有EF存储库,表格在哪里:

public DbSet<Request > Request { get; set; }
public DbSet<Approval> Approvals { get; set; }

我可以在我的RepositoryContext中定义它们是如何被查询的:

IQueryable<Approval> IRepository.Approvals {
    get { return Approvals.Where(a => !a.Flagged); }
}

因此,当我查询我的批准时,他们现在总是没有被标记:

_repository.Approvals.DoWhatEverWithThese() // these are always not flagged

另一方面,我的对象附有一份批准清单。

public class Request {
     public virtual List<Approval> Approvals { get; set; }
}

当我直接从请求中获取Approvals时,他们已在内部标记了Approvals。我如何预先选择批准,他们不会在其中标记项目。

我为域对象尝试了ExtensionMethods和[NotMapped]属性,但这些都给出了错误。

public static IEnumerable<Approval> NotFlaggedApprovals(this Request request) {
    return request.Approvals.Where(a => !a.Flagged);
}

[NotMapped]
public List<Approval> NotFlaggedApprovals{
    get { return Approvals == null ? new List<Approval>() : Approvals.Where(a => !a.Flagged).ToList(); }
} 


LINQ to Entities does not recognize the method 'NotFlaggedApprovals' method, and this method cannot be translated into a store expression.

如何预选?所以我不必总是这样写,很多样板:

_repository.Approvals.Where(a => !a.Flagged)

1 个答案:

答案 0 :(得分:0)

您是否尝试将未映射的属性放入请求对象?

public partial class Request 
{
    public virtual List<Approval> Approvals { get; set; }

    [NotMapped]
    public List<Approval> NotFlaggedApprovals
    {
        get 
        { 
            return Approvals == null ? new List<Approval>() : Approvals.Where(a => !a.Flagged).ToList(); 
        }
    } 
}