在 linq-to-sql 中指定标识值
我试图在将新记录插入数据库之前设置标识字段的值,当我知道目标表已经为空时,我试图避免不必要地重新映射所有 FK 字段。
我本来希望这个问题: 如何手动在 LINQ-To-SQL 中设置身份字段(IDENTITY INSERT) 会回答我的问题,但是看过之后,接受的答案似乎仍然没有提供直接的答案。
字段定义是:
[Column(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "BigInt NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public long ID
{
get {}
set {}
}
然而,这一切都是忽略任何设置值,只使用数据库中的下一个值。我发现将 IsDbGenerate 更改为 false 只会成功地让应用程序抛出“当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'Project' 中插入标识列的显式值”。例外。
即使使用以下内容也无济于事:
newDb.ExecuteCommand("SET IDENTITY_INSERT Contact ON");
newDb.SubmitChanges();
newDb.ExecuteCommand("SET IDENTITY_INSERT Contact OFF");
I am trying to set an identity field's value before inserting the new record into the database, I am trying to save having to needlessly re-map all of the FK fields when I know the destination tables are empty already.
I had hoped that this question:
How do I MANUALLY set an Identity field in LINQ-To-SQL (IDENTITY INSERT)
would answer my problem however having looked it, the accepted answer still doesn't seem to provide a straight forward answer.
The field definition is:
[Column(Storage = "_ID", AutoSync = AutoSync.OnInsert, DbType = "BigInt NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)]
public long ID
{
get {}
set {}
}
All this does however is ignore any set value and just use the next value in the database. I have found that changing the IsDbGenerated to false only succeeds in having the application thrown an "Cannot insert explicit value for identity column in table 'Project' when IDENTITY_INSERT is set to OFF." exception.
Even using the following doesn't help:
newDb.ExecuteCommand("SET IDENTITY_INSERT Contact ON");
newDb.SubmitChanges();
newDb.ExecuteCommand("SET IDENTITY_INSERT Contact OFF");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案是使用 SqlConnection 并在使用该 SqlConnection 创建 MappingSource 之前调用 .Open()。
然后您需要做的就是在字段定义中将 IsDbGenerate 设置为 false。
所以从:
变成:
否则它将使用它自己的内部 SQL 连接池,并且您的
IDENTITY_INSERT
不起作用。但请记住在完成后关闭 SQL 连接。此外,更改字段定义将使其在正常插入时不会更新 ID 字段。The solution was to use a SqlConnection and calling .Open() before creating the MappingSource using that SqlConnection.
Then all that you need to do is set the IsDbGenerated to false in the field definition.
So From:
Becomes:
Otherwise it will use it's own internal SQL connection pooling and your
IDENTITY_INSERT
doesn't work. But remember to close the SQL Connection when you're finished. Also, changing the field definition is going to make it not update the ID field when you do inserts normally.