I'm trying to get count of Employees in a specific State in LINQ.
I have something like this :
States
     |
     Cities
          |
          Posts
              |
              Employees
How can I get Employees count by selected State in hand?
My Entities are :
public class Province : EntityBase
{
    public String ProvinceName { get; set; }
    public virtual IList<City> Cities { get; set; }
}
public class City : EntityBase
{
    public String CityName { get; set; }
    public virtual Province Province { get; set; }
    public virtual IList<Post> ElectricPosts { get; set; }
}
public class Post : EntityBase
{
    public String PostName { get; set; }
    public virtual City City { get; set; }
    public virtual IList<Employee> Employees { get; set; }
}
public class Employee : Person
{
    public virtual String FirstName { get; set; }
    public virtual String SureName { get; set; }
    public virtual Post ElectricPost { get; set; }
}
Edit : The interesting thing is I can get count of Posts without any problem and exception, but when I want to try the way in @HamletHakobyan post I'm getting NullReferenceException and I don't know why?
I'm not sure but try this:
var state = ((IObjectContextAdapter)context)
            .ObjectContext
            .CreateObjectSet<Province>("States") as ObjectQuery<Province>;
            // States is entitySetName
int count = state.Cities.Include("ElectricPosts.Employees")
                    .SelectMany(c => c.Posts)
                    .SelectMany(p => p.Employees)
                    .Count();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With