Steve S
Steve S

Reputation: 219

Entity Framework Count Parent rows that have a child record with a constraint

I have a parent and child table. It is a one to many relationship. I am trying to determine a way to count the number of parent records that have a child record with a constraint on both the child and parent.

Example: Count the number of parent records that were created today and have a child record that with a value of true in in the address column.

I am completely stumped.

Upvotes: 0

Views: 578

Answers (1)

AD.Net
AD.Net

Reputation: 13409

(from p in context.Parents
where p.CreatedOn.Date == DateTime.Now.Date
&& p.Children.Any(c=>c.Address != null) // or p.Children.Any(c=>c.Address == true)
select p).Count()

May be something like this?

You can also go from the children, for example:

(from c in context.Child
where c.Address == true && c.Parent.CreatedOn.Date == DateTime.Now.Date
select c.Parent).Distinct().Count()

In lambda expression, please note that I just used childObj.Address == true (most likely that condition is a bit different, but you should see the idea.

  context.ARC_Records
                      .Where(d => (d.Signed == false || d.Signed == null) 
                            && d.ChildObject.Any(c=>c.Address == true))
                     .Count();

Upvotes: 2

Related Questions