我正在尝试用标识主键将记录插入到表中。有时候,我需要设置pk。例如,这在创建已知的测试数据以进行可靠的集成测试或在孤立环境中调试生产问题时非常有用。
其他帖子说要执行sql语句:
private void IdentityInsertOK()
{
var sql = "set identity_insert ConfigSettings on " +
"delete from ConfigSettings where id =2 " +
"insert into ConfigSettings (Id,Name, value) values (2,'test ','testval') " +
"set identity_insert ConfigSettings off ";
using (var Db = SettingsHelper.CreateContext(ConnectionType.Syrius))
{
Db.Database.ExecuteSqlCommand(sql);
Db.SaveChanges();
}
}虽然SQL语句有效,但它击败了的提议/好处。(特别是防止SQL注入)。
我尝试了以下方法,但在context.SaveChanges上失败了
private static void InsertEmployee(EmployeeModel employee)
{
var emp = new Employee //The database employee record
{
EmployeeId = emp.EmployeeId,
FirstName = emp.FirstName,
...
};
using (var context = new EmployeeEntities())
{
try
{
context.Database.Connection.Open();
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employee ON");
context.Employees.Add(emp);
context.SaveChanges();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Employee OFF");
scope.Complete();
}
}
finally
{
context.Database.Connection.Close();
}
}
}获取DB错误:
当IDENTITY_INSERT设置为OFF时,无法在表“Employee”中插入标识列的显式值。
(显示每个“操作”都是自己的“批处理”)
(另一条帖子停留在使用ExecuteStoreCommand打开&关闭标识插入,但这似乎在EF5中消失了。)
我已经关闭了连接字符串中的连接池,但仍然没有joy。有什么办法让这件事成功吗?或者还有另一种方法--最佳实践--来做到这一点?
发布于 2016-11-28 10:59:55
出现此问题,因为您需要告诉EF键列(Id)不应该生成数据库。
[DatabaseGenerated(DatabaseGenerationOption.None)]或者通过modelBuilder:
Property(obj => obj.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
.HasColumnName("Id");https://stackoverflow.com/questions/17153316
复制相似问题