c# - 无法将自定义值插入标识列 - Entity Framework

标签 c# entity-framework entity-framework-4 entity-framework-4.1 identity

我正在尝试关闭标识以插入我自己的值,我遵循的步骤

  1. 将标识列的属性 StoredGeneratedPattern 值更改为 None
  2. 通过以 xml 格式打开,将 EDMX 文件中的属性 StoredGeneratedPattern 值更改为 None

尝试使用下面的代码

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
   int k = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client ON");
   Context.ClientInfoes.Add(testclient);
   result = Context.SaveChanges();
   int j = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client OFF");
   scope.Complete();
}

但是还是报错

Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF

我错过了什么吗?还有其他选择吗?

最佳答案

当您调用 TransactionScope.Complete 时,数据存储在数据库中,而不是当您调用 ClientInfoes.Add 或 Context.SaveChanges 时。所以您可以看到,当调用插入语句时,您已经关闭了 IDENTITY INSERT。

简单地重新排列事物...

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
   int k = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client ON");
   Context.ClientInfoes.Add(testclient);
   result = Context.SaveChanges();
   scope.Complete();
   int j = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client OFF");
}

更好的是,在事务之外对 IDENTITY_INSERT 进行所有更改,因为它的值是特定于 session 的(每个 session 只能为一个表打开它)。

关于c# - 无法将自定义值插入标识列 - Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12731163/

相关文章:

c# - 相当于 Modify Headers Firefox Addon 的 .NET Native 应用程序

.net - 如何处理 Entity Framework 中缺少主键的问题?

c# - 使用 Asp.Net WebApi + EF + Odata 深度插入数据

sql-server - 存储过程和 Entity Framework 4.0 中的表值参数

c# - EF Core 5 - 如何将 EF.Functions.Like 与映射到 JSON 字符串的自定义属性一起使用?

c# - 用 C# 编写的托管 OleDB 提供程序

entity-framework - 防止 EF 保存完整的对象图

entity-framework - 模型中的多个图表与一个大型 .EDMX 与多个 .EDMX

c# - Response.TransmitFile 损坏文件

c# - EF6 代码第一个多重一对多映射问题/"Multiplicity"错误