我正在使用 Visual Studio 2012 将实体框架 4.1 / MVC 3 更新到实体框架 5.0 / MVC 4。数据库是 SQL Server 2005。下面是数据库表及其关系的图像。每个表都有一个主键。辅助表中的主键是 Identity。表由 FormId 关联。
当我从 Database 更新时,EF 会导入表及其关系。
使用 EF 4.1,我能够编写以下代码,通过一次 SaveChanges() 调用成功保存(插入)到所有四个表中。我以编程方式创建了一个新的 GUID,并将 nsForm 添加到其他三个表中。执行 SaveChanges() 时,EF 4 首先保存 NSForm 并在保存每个表时自动将 FormId 应用于其他三个表。
DateTime currentDateTime = DateTime.Now;
Guid formGuid = System.Guid.NewGuid();
bool success = false;
using (var context = new NSAFormsEntities())
{
NSAFormsEDM.NSForm nsForm = new NSAFormsEDM.NSForm();
SpeakerphoneForm speakerphoneForm = new SpeakerphoneForm();
NSAFormsEDM.Requestor requestor = new NSAFormsEDM.Requestor();
NSAFormsEDM.Authorizer authorizer = new NSAFormsEDM.Authorizer();
nsForm.FormGuid = formGuid;
nsForm.Form = "Speakerphone";
nsForm.CreateDate = currentDateTime;
nsForm.ModifiedBy = currentUser;
#region Speakerphone
speakerphoneForm.FormGuid = formGuid;
speakerphoneForm.ServiceDate = speakerphoneVM.ServiceDate;
speakerphoneForm.LocationId = speakerphoneVM.LocationId;
speakerphoneForm.CreateDate = currentDateTime;
speakerphoneForm.CreatedBy = currentUser;
speakerphoneForm.NSForm = nsForm;
#endregion
#region Requestor
requestor.FormGuid = formGuid;
requestor.NetworkId = currentUser;
requestor.CreateDate = currentDateTime;
requestor.CreatedBy = currentUser;
requestor.NSForm = nsForm;
#endregion
#region Authorizer
authorizer.FormGuid = formGuid;
authorizer.NetworkId = authorizerVM.NetworkId;
authorizer.CreateDate = currentDateTime;
authorizer.CreatedBy = currentUser;
authorizer.NSForm = nsForm;
#endregion
context.NSForms.Add(nsForm);
context.SaveChanges();
success = true;
}
现在,使用 EF 5.0 仅插入 NSForm 中的数据。显然,EF 5 不再将表格关系中表示的 FormId 键传播到三个辅助表
问题:应该如何编写使用 EF 5 的代码,以便通过一次 SaveChanges() 调用将数据插入到所有表中?
谢谢,
阿诺德