繁体   English   中英

掌握EF Core的儿童人数

[英]Getting count of children with EF Core

这些是我的实体:

public class Model {
    public int Id { get; set; }
    public string Name { get; set; }
    [NotMapped] // EDIT: Forgot to add this in my sample code.
    public bool HasChildren { get; set; }
    public ICollection<ChildModel> Children { get; set; }
}

public class ChildModel {
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
}

现在,我想做的是,如果有与Model相关的ChildModels,则拉出所有Model对象并将其HasChildren属性设置为true。 我现在是这样的:

context.Models.Select(s => new Model {
    Id = s.Id,
    Name = s.Name,
    HasChildren = s.Children.Count() > 0
});

我将结果投影到具有相同实体类型(模型)的集合中的方式感觉不对。

我也检查了生成的查询。 可以在单个查询中提取数据,这很好,但是我想知道是否有更好的方法使用C#做到这一点?

您可以使用Any代替count

context.Models.Select(s => new Model {
    Id = s.Id,
    Name = s.Name,
    HasChildren = s.Children.Any()
});

尝试使用以下模型定义:

public class Model {
    public int Id { get; set; }
    public string Name { get; set; }
    [NotMapped]
    public bool HasChildren => this.Children != null && this.Children.Count > 0;
    public ICollection<ChildModel> Children { get; set; }
}

如果不能使用C#6功能,则:

public bool HasChildren { get { return this.Children != null && this.Children.Count > 0; } }

EF Linq:

context.Models.Include(x => x.Children).ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM