I have a simple categories management system.
In my auto-generated EF entities I have two classes of relevance:
class Category {
public EntityCollection<Member> Members { get; }
}
class Member {
public Category ParentCategory { get; }
}
I have a business rule that prevents the deletion of a category if it has any members. I was hoping to accomplish that by doing this:
if( category.Members.Count() > 0 ) // then disallow deletion
However this call always returns zero.
It appears that I need to actually load the collection first, which incurrs a DB hit:
if( !category.Members.IsLoaded ) category.Members.Load();
if( category.Members.Count() > 0 ) // then disallow deletion. This works.
I was hoping that the EF would be smart enough to convert the initial .Count() call into the SQL SELECT COUNT(*) FROM Members WHERE Members.CategoryId = @parentCategoryId instead of actually loading Members entities and iterating through them in-memory.
Is there a way to do that in EF, or do I need to define a sproc or custom SQL to achieve this?
Try