C# 在实体框架的下一次插入中使用标识的多个插入
我有以下代码片段试图使用EntityFramework6.0.2执行多个插入。我正在使用本文中讨论的C# 在实体框架的下一次插入中使用标识的多个插入,c#,entity-framework,transactions,C#,Entity Framework,Transactions,我有以下代码片段试图使用EntityFramework6.0.2执行多个插入。我正在使用本文中讨论的数据库.BeginTransaction() using(var context = new Sys.EntityModels.ERPPermissionMgmtEntities()) { using (var dbContextTran = context.Database.BeginTransaction()) { try {
数据库.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\u Role\u Mapping
表时使用。如何从第一次插入开始保护记录标识,而不在BeginTransaction
using语句之外进行单独的插入在添加应用程序后添加对SaveChanges()
的调用。实体框架将为您修复ID:
//add the application information to the Applications database table
context.Applications.Add(a);
context.SaveChanges();
applicationId = a.ApplicationId;
谢谢我试图实现
SaveChanges(false)
和AcceptAllChanges
,但这些仅在ObjectContext
中可用,而不是DbContext
对象类型