views:

458

answers:

1

I'm engaged in writing a product using LinqToSql for data-access. While we're rapidly developing, the model changes often. This means we dump and reload the database lots while developing. Thus, overhead is involved to recreate baseline data each time.

A process that restores a DB backup is not useful, because we would need to update the model DB just as often; same overhead (I think, anyway).

So, I want to use DataContext.CreateDatabase, then pull some data in from CSV files. Fine. But I would also like to stitch up the relationships, which means, ideally, knowing what the primary keys will be in advance (otherwise, given that some identities are GUIDs, it will be hard to stitch up the links I need to).

What is the equivalent to SET IDENTITY_INSERT IdentityTable ON (and OFF) in Linq To SQL? Is there one?

+1  A: 

You don't need to know the primary keys in advance, you only need to know the relationships.

Suppose you wanted to load in Customers and Orders, where a Customer has many Orders.

First load in your Customers from the file into memory, use a fake primary key value from the file for CustomerId (this value will be replaced by an autogenerated one by the database later).

Dictionary<int, Customer> customers = LoadCustomersFromFile();

Second, load in your Orders from the file into memory. use a fake primary key value for OrderId. Re-use those fake CustomerIds to establish relationships. Add the orders to their related customers.

Dictionary<int, Order> orders = LoadOrdersFromFile();
foreach(Order o in orders.Values)
{
  customers[o.CustomerId].Orders.Add(o);
}

After the object graph is constructed, InsertOnSubmit all of the objects.

David B