[英]How do I insert entities with Linq To SQL where I wish to specify their identities - eg, pre-populating tables on DB creation?
I'm engaged in writing a product using LinqToSql for data-access. 我从事使用LinqToSql进行数据访问来编写产品。 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. 因此,我想使用DataContext.CreateDatabase,然后从CSV文件中提取一些数据。 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).
但是我也想缝合这些关系,这意味着,理想情况下,要事先知道主键是什么(否则,鉴于某些身份是GUID,将很难缝合我需要的链接)。
What is the equivalent to SET IDENTITY_INSERT IdentityTable ON
(and OFF) in Linq To SQL? 与Linq To SQL中的
SET IDENTITY_INSERT IdentityTable ON
(和OFF)等效吗? Is there one? 有一个吗?
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). 首先将客户从文件加载到内存中,然后使用文件中的假主键值作为客户ID(稍后该值将由数据库自动生成的值替换)。
Dictionary<int, Customer> customers = LoadCustomersFromFile();
Second, load in your Orders from the file into memory. 其次,将订单从文件加载到内存中。 use a fake primary key value for OrderId.
为OrderId使用伪造的主键值。 Re-use those fake CustomerIds to establish relationships.
重用那些假的CustomerId来建立关系。 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. 构造对象图之后,InsertOnSubmit提交所有对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.