Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Count Of Nested Entities

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?

like image 353
saber Avatar asked Jan 22 '13 14:01

saber


1 Answers

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();
like image 146
Hamlet Hakobyan Avatar answered Oct 26 '22 10:10

Hamlet Hakobyan