在下一个INSERT与实体框架中使用Identity的多个插入

时间:2014-03-25 23:24:38

标签: c# entity-framework transactions

我有以下代码片段尝试使用Entity Framework 6.0.2执行多个插入。我在MSDN Working with Transactions (EF6 Onwards)文章中使用Database.BeginTransaction()讨论。

using(var context = new Sys.EntityModels.ERPPermissionMgmtEntities())
{
    using (var dbContextTran = context.Database.BeginTransaction())
    {
        try
        {
            if (application.Id == 0)
            {
                Sys.EntityModels.Applications a = ConvertObjToEntity(application);

                //add the application information to the Applications database table
                context.Applications.Add(a);

                applicationId = a.ApplicationId;
            }

            //loop through the Roles property list to add the Application/Role relationship to the Application_Role_Mappings table
            if (application.Roles != null)
            {
                foreach (Entity.Role role in application.Roles)
                {
                    if (role.Id == 0)
                    {
                        Sys.EntityModels.Roles r = ConvertObjToEntity(role);

                        //add the role information to the Roles table
                        context.Roles.Add(r);

                        roleId = r.RoleId;
                     }


                     //insert a Application/Role mapping into the Application_Role_Mappings table
                     Sys.EntityModels.Application_Role_Mappings arm = new Sys.EntityModels.Application_Role_Mappings
                     {
                         ApplicationId = applicationId,
                         RoleId = roleId,
                         CreatedBy = application.CreatedBy.EmployeeID,
                         DateTimeCreated = System.DateTime.Now
                     };

                     context.Application_Role_Mappings.Add(arm);
                 }
             }

             SaveChanges(context);

             dbContextTran.Commit();
        }
        catch(Exception)
        {
            dbContextTran.Rollback();
            updateSuccessful = false;
        }
    }
}

当我将Sys.EntityModels.Application对象插入Applications表时,我需要在插入记录到Application_Role_Mapping表时使用该插入的标识。如何在第一次插入时保护记录标识,而不在BeginTransaction using statement

之外单独插入

1 个答案:

答案 0 :(得分:1)

添加应用程序后,添加对SaveChanges()的调用。实体框架将为您修复ID:

//add the application information to the Applications database table
context.Applications.Add(a);
context.SaveChanges();
applicationId = a.ApplicationId;