使用Entity框架过滤相关实体

时间:2012-04-29 22:38:28

标签: entity-framework filtering

我正在寻找加载和过滤相关子实体的最佳方法。我有一些有用的东西,但我不确定它是否是实现我想要的最好甚至是正确的方法。下面的工作代码示例。优点和缺点会很棒!谢谢!

public Site Find(int siteID)
{
    // Can't use include here, not possible to filter related (child) entities
    // return _context.Sites.Where(x => x.ID == siteID)
    //                      .Include("SiteLoggers")
    //                      .Where(x => x.Deleted == false)
    //                      .FirstOrDefault();

    var site = _context.Sites.Where(x => x.ID == siteID).FirstOrDefault();

    if(site != null)
    {
        site.SiteLoggers = site.SiteLoggers.Where(x => x.SiteID == siteID && 
                                                       x.Deleted == false)
                                           .ToList();
    }

    return site;
}

编辑:

添加了POCOS

public class Site
{
    public int ID { get; set; }
    public int LocationID { get; set; }
    public bool Active { get; set; }
    public bool Deleted { get; set; }
    public string Name { get; set; }
    public virtual Location Location { get; set; }
    public virtual ICollection<SiteLogger> SiteLoggers { get; set; }
    public virtual ICollection<LinkDcSite> DcSiteLinks { get; set; }
}

public class SiteLogger
{
    public int ID { get; set; }
    public int UID { get; set; }
    public int SiteID { get; set; }
    public int LocationID { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
    public bool Deleted { get; set; }
    public virtual Site Site { get; set; }
    public virtual Location Location { get; set; }
    public virtual ICollection<SiteLoggerSensor> SiteLoggerSensors { get; set; }
    public virtual ICollection<LinkLoggerSiteLogger> LinkLoggerSiteLogger { get; set; }
}

2 个答案:

答案 0 :(得分:1)

您的方法很好我认为您只需要额外检查x.SiteID == siteID

....
site.SiteLoggers = site.SiteLoggers.Where(x => !x.Deleted).ToList();
....

此外,如果您通过ID搜索意味着您确定没有两个具有相同ID的元素,那么最好使用SingleOrDefault而不是FirstOrDefault,以便在有多个具有一个ID的项目的情况下抛出异常。 / p>

var site = _context.Sites.Where(x => x.ID == siteID).SingleOrDefault();

答案 1 :(得分:0)

您可以使用简单的查询来执行此操作:

var site = _context.SiteLoggers.Where(sl => sl.SiteId = siteId && !sl.Deleted).ToList();

如果SiteLoggers与站点之间存在关联,则无需确定该站点是否存在。