在插入父对象和子对象之前添加子对象

时间:2011-08-04 12:30:32

标签: entity-framework entity-framework-4 ado.net entity-framework-4.1 ado.net-entity-data-model

我完成了Nerd Dinner应用程序。在Create action方法中,它们具有以下代码:

NerdIdentity nerd = (NerdIdentity)User.Identity;
dinner.HostedById = nerd.Name;
dinner.HostedBy = nerd.FriendlyName;

RSVP rsvp = new RSVP();
rsvp.AttendeeNameId = nerd.Name;
rsvp.AttendeeName = nerd.FriendlyName;
dinner.RSVPs.Add(rsvp);

dinnerRepository.Add(dinner);
dinnerRepository.Save();

我首先使用Entity Framework 4.1代码。

这是我的GrantApplication课程:

public class GrantApplication
{
   public int Id { get; set; }
   // Other properties
   public virtual ICollection<AuditEntry> AuditEntries { get; set; }
}

在我的服务层中,我执行以下操作,与Nerd Dinner的操作相同:

public void Insert(GrantApplication grantApplication)
{
   // Add audit entry
   grantApplication.AuditEntries.Add(new AuditEntry
   {
      NewValue = grantApplication.GrantApplicationStateId,
      AuditDate = currentDateTime,
      EmployeeNumber = submitterEmployeeNumber
   });

   // Insert the new grant application
   grantApplicationRepository.Insert(grantApplication);
}

我的AuditEntry类:

public class AuditEntry
{
   public int Id { get; set; }
   public int OldValue { get; set; }
   public int NewValue { get; set; }
   public DateTime AuditDate { get; set; }
   public string EmployeeNumber { get; set; }
}

我的上下文类:

public class HbfContext : DbContext
{
   public DbSet<Bank> Banks { get; set; }
   public DbSet<AccountType> AccountTypes { get; set; }
   public DbSet<GrantApplication> GrantApplications { get; set; }
   public DbSet<AuditEntry> AuditEntries { get; set; }

   protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
   {
   }
}

我收到一个错误,即grantApplication.AuditEntries为null,因此无法添加审计条目对象。为什么我的是null,但是当它试图添加RSVP obkect时,RSVP不为空?我该如何解决?

我是否需要将AuditEntries添加到HbfContext?我的意思是我不打算单独使用它。它仅在编辑GrantApplication时使用。

更新

我必须使用较旧版本的Nerd Dinner,但这就是我的Create看起来的样子:

[HttpPost, Authorize]
public ActionResult Create(Dinner dinner)
{
   if (ModelState.IsValid)
   {
      NerdIdentity nerd = (NerdIdentity)User.Identity;
      dinner.HostedById = nerd.Name;
      dinner.HostedBy = nerd.FriendlyName;

      RSVP rsvp = new RSVP();
      rsvp.AttendeeNameId = nerd.Name;
      rsvp.AttendeeName = nerd.FriendlyName;
      dinner.RSVPs.Add(rsvp);

      dinnerRepository.Add(dinner);
      dinnerRepository.Save();

      return RedirectToAction("Details", new { id=dinner.DinnerID });
   }

   return View(dinner);
}

1 个答案:

答案 0 :(得分:1)

嗯,因为NerdDinner DinnersController.Create includes a line of code which you didn't show

            dinner.RSVPs = new List<RSVP>(); // why is this not in your example?
            dinner.RSVPs.Add(rsvp);
  

我是否需要将AuditEntries添加到HbfContext?

是的,你这样做。那么,你必须以某种方式将它们添加到你的EF模型中。这是一种方法。您也可以使用OnModelCreating中的代码执行此操作。