I worked through the Nerd Dinner
application. In the Create action method they have the following code:
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();
I am using Entity Framework 4.1
code first.
Here is my GrantApplication
class:
public class GrantApplication
{
public int Id { get; set; }
// Other properties
public virtual ICollection<AuditEntry> AuditEntries { get; set; }
}
In my service layer I do the following, the same as what Nerd Dinner does it:
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);
}
My AuditEntry class:
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; }
}
My context class:
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)
{
}
}
I get an error that grantApplication.AuditEntries is null so it can't add the audit entry object. Why is mine null, but dinner.RSVPs is not null when it tries to add the RSVP obkect? How would I fix it?
Do I need to add AuditEntries to HbfContext? I mean I'm not going to use it on it's own. It will only be used when a GrantApplication is edited.
UPDATE
I must be using an older version of Nerd Dinner, but this is what my Create looks like:
[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);
}
Um, because the 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);
Do I need to add AuditEntries to HbfContext?
Yes, you do. Well, you have to add them to your EF model in some way. That's one way to do it. You might be able to do it with code in OnModelCreating
as well.