实体框架4.2,无法设置标识插入ON

tam*_*tam 11 c# asp.net asp.net-mvc ado.net entity-framework-4.1

我想将批量记录添加到具有给定ID的表中,这样我就可以构建一个以树视图方式显示记录的层次结构.我可以单独添加工作正常的记录,但我没有设置ID.我想只批量设置ID,所以我在我的实体的id列中设置DatabaseGeneratedOption None作为None.

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{

     foreach (ErrorCode ec in errorCodesStep3.errorcodesUsers)
     {

           errorCode.ID = ec.ID;
           errorCode.ParentID = ec.ParentID;
           errorCode.ErrorDescription = ec.ErrorDescription;
           db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.ErrorCode ON");
           db.ErrorCode.Add(errorCode);
           db.SaveChanges();    
           scope.Complete();
     }
}
Run Code Online (Sandbox Code Playgroud)

错误代码

[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
Run Code Online (Sandbox Code Playgroud)

我收到的错误是:

当标识插入为OFF时,无法设置标识.

不确定什么是错的,因为我已经看到了可以打开身份插入的示例.我使用的是EF版本4.2.0.0和运行时版本v4.0.30319.我可以通过executeSQL参数化变量轻松添加INSERT语句,但我想用实体框架来做.似乎db.Database.ExecuteSqlCommand是在一个单独的范围内,它立即关闭,并在db.savechanged执行时不可用.

Den*_*nov 1

试试这个:带有身份插入的实体框架

也许是这样:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
    using (var db = new Context()) // your Context
    {
        db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.ErrorCode ON");
        ErrorCode errorCode = db.ErrorCode.First(); // for example
        foreach (ErrorCode ec in errorCodesStep3.errorcodesUsers)
        {
            errorCode.ID = ec.ID;
            errorCode.ParentID = ec.ParentID;
            errorCode.ErrorDescription = ec.ErrorDescription;    
            db.ErrorCode.Add(errorCode);
        }
        db.SaveChanges();
        db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.ErrorCode OFF");
        scope.Complete();
    }
}
Run Code Online (Sandbox Code Playgroud)