How do I insert objects with Linq To SQL where I want to specify their ids - for example, pre-populating tables when creating a DB?

I am writing a product using LinqToSql for data access. While we are developing rapidly, the model changes frequently. This means we dump and reload the database lots during development. Thus, overhead is used to recreate the original data every time.

The process that restores the database backup is not useful because we will need to update the model database just as often; the same overhead (I think anyway).

So, I want to use DataContext.CreateDatabase and then pull some data from CSV files. Good. But I would also like to stitch the relationship, which means, ideally, knowing which primary keys will be ahead of time (otherwise, given that some ids are GUIDs, it would be difficult to stitch the links I need together).

What's the equivalent SET IDENTITY_INSERT IdentityTable ON

(and OFF) in Linq To SQL? There is one?

0


source to share


1 answer


You don't need to know the primary keys ahead of time, you need to know the relationship.

Let's say you wanted to upload to Clients and Orders, where the Client has many orders.

First load your customers from file into memory, use fake primary key value from file for CustomerId (this value will be replaced with database autogenerated later).

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

      



Second, load into your Orders from file into memory. use a fake primary key value for OrderId. Reuse these fake CustomerIds to establish relationships. Add orders to your related customers.

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

      

After building the object graph, InsertOnSubmit all objects.

+2


source







All Articles