Reputation: 4503
I have two tables which are related in the database: ChangeOrder and Auditor. ChangeOrder has a foreign key AuditorId field which points to the Auditor record.
Entity Framework built the relationship as
public partial class ChangeOrder
{
public int Id { get; set; }
public Nullable<int> ActiveContractId { get; set; }
public virtual Auditor Auditor { get; set; }
Whenever I change the AuditorId I don't see the related Auditor entity in ChangeOrder updating, before the change when the Entity loads it's fine, the correct AuditorId and Auditor.Name come back, however, when I mark the ChangeOrder.State = State.Modified, the Auditor entity becomes null, even after the save is called the AuditorId is updated, but the Auditor record is null.
I'm using the Repository Pattern:
ChangeOrder co;
using (UnitOfWork uow = new UnitOfWork())
{
using (ChangeOrderRepository changeOrderRepos = new ChangeOrderRepository(uow))
{
co = changeOrderRepos.All.Where(x => x.Id == id).Include(x => x.Auditor).FirstOrDefault();
// before this AuditorId = 1 and Auditor.Name is "Apple"
co.AuditorId = auditorNameId == -1 ? null : auditorNameId;
// now AuditorId = 2 and Auditor.Name is still "Apple", 2 = "Orange", but i have not saved so i get why it didn't change here
co.State = State.Modified;
changeOrderRepos.InsertOrUpdate(co);
}
uow.Save();
}
The InsertOrUpdate method is:
public void InsertOrUpdate(ChangeOrder entity)
{
if (entity.State == State.Added) // New entity
{
_context.Entry(entity).State = EntityState.Added;
}
else // Existing entity
{
_context.Entry(entity).State = EntityState.Modified;
}
}
When the method is first called the AuditorId is 2, and Auditor.Name is "Apple" as soon as the State is changed to Modified, the AuditorId is still 2, but the Auditor object is null.
The Save method on the UnitOfWork class:
public int Save()
{
return _context.SaveChanges();
}
If I lookup the record again, the object has the correct name (Orange), I just dont't understand why after I did the save the Entity doesn't get the Auditor record updated as well.
Upvotes: 2
Views: 1511
Reputation: 4503
I found something here that helped: http://msdn.microsoft.com/en-us/data/jj713564.aspx
In the Loading Related Objects section, I had to run the following after the InsertOfUpdate call:
_context.Entry(entity).Reference(c => c.Auditor).Load();
This caused the navigational property to reload, so Auditor.Name was "Orange" as it should have been.
Upvotes: 2