Thursday, 29 August 2013

Updating foreign key references on the DbContext ChangeTracker

Updating foreign key references on the DbContext ChangeTracker

I work with EF 5.0, DB first in a web project.
For our service layer, we use Agatha with AutoMapper, so all data arrives
in the service layer as POCO objects.
I have a data structure that look like this:
public class FirstClass
{
public int Id { get; set; }
public int? SelectedSecondClassId { get; set; }
public SecondClass SelectedSecondClass { get; set; }
public ICollection<SecondClass> MySecondClasses { get; set; }
//other properties go here
}
public class SecondClass
{
public int Id { get; set; }
public int ParentSecondClassId { get; set }
public SecondClass ParentSecondClass { get; set; }
//other properties go here
}
Now imagine I try to update a FirstClass object and do the following in 1 go:
Create 2 new Secondclass objects in the MySecondClasses collection (both
with id 0)
Set one of these newly created objects as the SelectedSecondClass
Then EF refuses to play ball. I can't get it to work. If I look in the
changetracker, I see that the SelectedSecondClass on the entity is empty
again, but the SelectedSecondClassId is set to 0. And that's something he
can't resolve, because there are 2 objects with Id 0, before they are
properly created.
If I do this, I can get stuff fixed:
var newId = -1;
foreach (var newSecondClass in firstClass.MySecondClasses.Where(x => x.Id
<= 0))
{
newSecondClass.Id = newId;
newId --;
}
if (firstClass.SelectedSecondClass != null)
{
firstClass.SelectedSecondClassId = firstClass.SelectedSecondClass.Id;
}
// Send the updates to EF
As you understand, I feel like this is a bit hacked together and it would
be easy for another developer to forget something like this. I would like
to have a better way of doing this. Preferably in a way that I can 'fix'
situations like this just before a SaveChanges() in my DbContext wrapper.
Can anybody point me in the right direction?

No comments:

Post a Comment