实体框架5标识插入



我试图将一条记录插入到具有身份主键的表中。有时,我需要设置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();
            }
        }
    }

get DB error:

当IDENTITY_INSERT设置为OFF时,不能在表'Employee'中插入标识列的显式值。

(SQL Profiler显示每个'action'都是它自己的'batch')

(另一个帖子使用ExecuteStoreCommand打开&从标识插入中删除,但在EF5中似乎没有了。

我已经关闭了连接字符串中的连接池,但仍然没有乐趣。有什么好主意吗?或者是否有其他方法——最佳实践——来做到这一点?

出现这个问题是因为您需要告诉EF键列(Id)不应该是数据库生成的。

[DatabaseGenerated(DatabaseGenerationOption.None)]

或通过modelBuilder:

Property(obj => obj.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
    .HasColumnName("Id");

相关内容

最新更新