tags:

views:

12

answers:

1

I have an object with nested parts persisted over three tables. The classes are POCO with IList<> for relations. No ties to any framework.

A_object-> B_object[N]-> C_object[N]

I send this object to a repository to update. The repository persists content using Linq to SQL.

myRepo.Update(A_object);

The first loop that handles updates and deletes:

foreach (var B in A.B_records) 
{    foreach (var C in B.C_records) 
     {
         if( C is in our parameter object)
             // update the database object
         else
             // not found, delete the database object
     }

     if( B is in our parameter object)
         // update the database object
     else
         // not found, delete the database object
}

The loop updates the database record if found in our parameter object, or deletes the database record if not found in our parameter object. Thus updates and deletes are working fine.

Given that I cannot modify the class of the parameter object, **is there some pattern or mechanic I could implement to insert missing B and C objects without requerying the database again?

Obviously I could create an Array for found B and C primary keys, then skip them on the insert loop, but is there a better way I am missing?

+1  A: 

We have a similar pattern where I'm working. Normally we do one of two things:

  1. Set a "IsNew" field to "true" on objects which were not in the database before, or
  2. Set the ID of the object to some invalid number as a "this is a new item" flag.
John Fisher
Ah, good idea. I knew two loops were too many.
Dr. Zim