首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体框架5身份插入

实体框架5身份插入
EN

Stack Overflow用户
提问于 2013-06-17 17:26:02
回答 1查看 2K关注 0票数 2

我正在尝试用标识主键将记录插入到表中。有时候,我需要设置pk。例如,这在创建已知的测试数据以进行可靠的集成测试或在孤立环境中调试生产问题时非常有用。

其他帖子说要执行sql语句:

代码语言:javascript
复制
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上失败了

代码语言:javascript
复制
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。有什么办法让这件事成功吗?或者还有另一种方法--最佳实践--来做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-11-28 10:59:55

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

代码语言:javascript
复制
[DatabaseGenerated(DatabaseGenerationOption.None)]

或者通过modelBuilder:

代码语言:javascript
复制
Property(obj => obj.Id)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)
    .HasColumnName("Id");
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17153316

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档