简体   繁体   中英

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. 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#?

You can use Any instead of count

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

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:

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

EF Linq:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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