Best way to check for dependant objects

Thread is closed for posting
2 posts, 0 answers
  1. IT
    IT avatar
    41 posts
    Member since:
    Jan 2010

    Posted 17 Aug 2011 Link to this post

    If I have two persisted classes, a parent and child with a one to many relationship what is the best way to check if the parent has any children?

    I know I can have constraints on the database to prevent me from deleting the parent when children are present, or I can set a dependency to cascade delete, however I want to be able to see if I *can* delete, without actually trying.

    I'd like to implement a CanDelete() property on my parent object, so that I can do things in the UI layer (like showing/hiding a delete button) depending on whether I can delete an object.

    Currently I'm checking the count of the child list to see if it has any members:-

    private IList<Child> children = new List<Child>();
    public IList<Child> Children { get { return children; } }
    public bool CanDelete() {
        return this.Children.Count == 0;

    But I'm thinking this might not be the most efficient way... I'm not sure if by calling Count I'm forcing OA to load all children at a time when I might not need them.

    Does anyone know of a better way to check for these dependant objects without having to load them?

    Many thanks...
  2. Nikola
    Nikola avatar
    27 posts

    Posted 18 Aug 2011 Link to this post

    Hello Aleks,

    What your code does currently is triggering the lazy loading of the Children which results into executing a full scale query that fetches all of the data in the Children table, filtered by the primary key of the current Parent. To put it short - it's not very efficient. On the other hand though, your code is clean and readable so I wouldn't be too quick on removing it. I would personally choose this approach if I am working with relatively small chunks of data where the drawback of loading a bit more data from the database will not hurt the user experience.

    What you can do to speed up the process is to work directly with the OpenAccessContext and call Count() on the Children object. Something like this:

            public bool CanDelete()
                IObjectScope scope = Database.GetContext(this) as IObjectScope;
                if (scope == null)
                    return false;
                return scope.Extent<Child>().Count(p => p.ParentID == this.ParentID) == 0;

    As you can see, this code is a bit more complicated but will trigger only a select count() statement into the database. 
    Hope that helps and have a nice day.

    Greetings, Nikola
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get now >>

Back to Top