Reputation: 5914
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#?
Upvotes: 1
Views: 3053
Reputation: 631
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();
Upvotes: -1
Reputation: 69032
You can use Any instead of count
context.Models.Select(s => new Model {
Id = s.Id,
Name = s.Name,
HasChildren = s.Children.Any()
});
Upvotes: 4