Re-use of database object in sub-sonic

110 Views Asked by At

Yet another newbie SubSonic/ActiveRecord question. Suppose I want to insert a couple of records, currently I'm doing this:

using (var scope = new System.Transactions.TransactionScope())
{
    // Insert company
    company c = new company();
    c.name = "ACME";
    c.Save();

    // Insert some options
    company_option o = new company_option();
    o.name = "ColorScheme";
    o.value = "Red";
    o.company_id = c.company_id;
    o.Save();
    o = new company_option();
    o.name = "PreferredMode";
    o.value = "Fast";
    o.company_id = c.company_id;
    o.Save();

    scope.Complete();
}

Stepping through this code however, each of the company/company_option constructors go off and create a new myappDB object which just seems wasteful.

Is this the recommended approach or should I be trying to re-use a single DB object - and if so, what's the easiest way to do this?

2

There are 2 best solutions below

0
On

I believe you can use the same object if you want to by setting its IsNew property to true, then change its data properties, save it again, repeat. Easy enough.

I 'm not so sure that you should bother, though. It depends on how bad those constructors are hurting you.

0
On

In my eyes assigning multiple objects to a single var is never a good idea but thats arguable. I would do this:

// Insert some options
company_option o1 = new company_option();
o1.name = "ColorScheme";
o1.value = "Red";
o1.company_id = c.company_id;
o1.Save();

company_option o2 = new company_option();
o2.name = "PreferredMode";
o2.value = "Fast";
o2.company_id = c.company_id;
o2.Save();

I you are worried about performance, that shouldn't be a issue unless you want to insert or update many objects at once. And again, in this case the time used for inserting the data takes longer than for the object creation.

If you are worried about performance you can skip the object creation and saving part completly by using a Insert query:

http://www.subsonicproject.com/docs/Linq_Inserts

   db.Insert.Into<company_option>(
     x => x.name, 
     x => x.value,
     x => x.company_id)
    .Values(
        "ColorScheme",
        "Red",
        c.company_id
    ).Execute();