实体框架5 SaveChanges不会将数据保存到所有相关表

时间:2012-11-07 17:04:31

标签: sql-server visual-studio-2012 entity-framework-5

我正在使用Visual Studio 2012将实体Framerwork 4.1 / MVC 3更新到Entity Framework 5.0 / MVC 4.数据库是SQL Server 2005.下面是数据库表及其关系的图像。每个表都有一个主键。辅助表中的主键是Identity。表与FormId相关。

Database Tables

当我从数据库更新时,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()调用将数据插入到所有表中?

谢谢,

阿诺德

0 个答案:

没有答案