我有以下代码片段尝试使用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
答案 0 :(得分:1)
添加应用程序后,添加对SaveChanges()
的调用。实体框架将为您修复ID:
//add the application information to the Applications database table
context.Applications.Add(a);
context.SaveChanges();
applicationId = a.ApplicationId;