[英]Getting count of children with EF Core
These are my entities: 这些是我的实体:
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; }
}
Now what I want to do is, pull all the Model objects and set their HasChildren properties to true, if there are ChildModels related to the Model. 现在,我想做的是,如果有与Model相关的ChildModels,则拉出所有Model对象并将其HasChildren属性设置为true。 This is how I do it now: 我现在是这样的:
context.Models.Select(s => new Model {
Id = s.Id,
Name = s.Name,
HasChildren = s.Children.Count() > 0
});
Which kind of feels like something is off with the way I project the result into a collection with the same type of the entity (Model). 我将结果投影到具有相同实体类型(模型)的集合中的方式感觉不对。
Also I checked the generated query. 我也检查了生成的查询。 The data is pulled in a single query which is nice but I wonder if there is a better way to do this with C#? 可以在单个查询中提取数据,这很好,但是我想知道是否有更好的方法使用C#做到这一点?
Try with this model definition: 尝试使用以下模型定义:
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; }
}
If you can not use C#6 features, than: 如果不能使用C#6功能,则:
public bool HasChildren { get { return this.Children != null && this.Children.Count > 0; } }
EF Linq: EF Linq:
context.Models.Include(x => x.Children).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.