I'll try to update my entity after setting a new FOREIGN KEY
value.
My (simplified) entities are:
public class FirstEntity
{
public Guid Id { get; set; }
public Guid SecondEntityId {get; set;} // <-- this is the FK
public virtual SecondEntity SecondEntity { get; set; } // <-- this is the navigation property
}
public class SecondEntity
{
public Guid Id { get; set;}
public virtual ICollection<FirstEntity> FirstEntity { get; set; }
}
At some point in my code I want to change the reference for an object of type FirstEntity
by setting the FK-value to a new value.
var theFirstEntity = DbContext.FirstEntity.Single(f => f.Id == Guid.Parse("5e27bfd3-d65b-4164-a0e4-93623e1b0de0"));
// at this point theFirstEntity.SecondEntityId is 'e06f8909-98f9-4dc6-92ec-49d9a6aac831'
theFirstEntity.SecondEntityId = Guid.Parse("C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44"); // <-- existing Id from database
// now theFirstEntity.SecondEntityId is 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44'
// but the reference theFirstEntity.SecondEntity is still pointing the 'old' entity with id 'e06f8909-98f9-4dc6-92ec-49d9a6aac831'
// but it should have id 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44
Now I try to load the new reference explicitly using
DbContext.Entry(FirstEntity).Reference(t => t.SecondEntity).Load();
as found here.
But FirstEntity.SecondEntity
stays the same System.Data.Entity.DynamicProxies.SecondEntity_XYZ
as it was before.
On the other side, when looking at DbContext.Entry(FirstEntity).Reference(t => t.SecondEntity).Query()
and the values of the Parameters
property, the query seems to be correct by looking after Id = 'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44'
.
Instead it should containt the correct entity of type SecondEntity
with the Id
'C5AB5CBA-5CD8-40B7-ABFB-C22F17646D44' and not the 'old' value.