C#/SQL Server 数据导入导出问题
我需要为三个与主键/外键约束内部相关的数据库表实现导入导出模块。
我可以使用 c#/linq to xml/linq to sql 轻松完成这两部分。问题是,当我导入导出的数据时,在数据库中,主键表的 id 会重新生成,而无需从 xml 文件获取/分配 id(它自然会自动递增)。为此,无法导入其他表数据/显示违反主键约束的错误。
我的目标是导入所有数据并保持主/外键完整。
现在,有人可以建议我做什么来解决这个问题吗?提前致谢。
I need to implement an import export module for three database tables which are internally related with primary key/foreign key constraints.
I can do both part easily using c#/linq to xml/linq to sql. Problem is, when i am importing the exported data, in database, primary key tables' id are regenerating without taking/assign the id from xml file(its natural for auto increment). For this, other tables data can't be imported/showing error that primary key constraint violates.
My goal is to import all data and keep the primary/foreign key intact.
Now, can anyone please suggest me what I can do to solve this issue please? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用身份插入指定身份列的值。
如果您为标识列指定显式值,则您自己负责解决冲突。如果数据库已包含
id = 1
行,则您必须决定在导入还包含id = 1
时该怎么做:SQL Server 将抛出错误。You can use identity insert to specify a value for identity columns.
If you specify explicit values for identity columns, you yourself are responsible for resolving conflicts. If the database already has a row with
id = 1
, you have to decide what to do if the import also containsid = 1
: SQL Server will just throw an error.我们总是使用 BCP 操作来完成此类任务。
We always used BCP operations for such tasks.
我建议不要让你的自动增量成为主键,而是有一个单独的主键,可以以其他方式定义......那么你就不会遇到自动增量的问题
I would suggest to not make your autoincrement the primary key but to have a separate primary key which can be defined somehow else... then you won't have the problem with the autoincrement
如果您不需要 XML 和 SQL 中的 id 进行匹配(仅需要关系),您可以使用
SCOPE_IDENTITY()
并维护从 XML id 到 SQL id 的映射,以便在其他表中正确插入外键列。If you don't need the ids in the XML and SQL to match (only the relationships) you could use
SCOPE_IDENTITY()
and maintain mapping from XML ids to SQL ids to insert properly foreign key columns in other tables.