First of all I am not an expert on Entity Framework.
And I have seen some piece of code in one project’s Repositories, which
- NULLs the EntityReference properties on the entity
- And keeps that EntityReference’s ID
before Saving changes of this entity.
For example it does this setting before saving Foo entity:
if (foo.Bar !=null)
{
foo.BarID = foo.Bar.ID;
foo.Bar = null;
}
Can this be an EntityFramework related requirement to null the EntityReference properties but using their IDs only in order to Save ?
No, normally that’s not a requirement. When working with attached entities for example you can change the FK property or the reference, both would work:
Then…
…would work and…
…will work as well. No need to null out the reference.
The code in your question would possibly make sense if
foo–foo.Barrelationship is in an inconsistent/contradicting stateFor example:
And
UpdateFoois:The
Attachline would throw an exception because the FK valueBarIDis4but the referencedfoo.Baris theBarnumber5. EF does not know what is valid and will refuse to write an Update.You could fix this problem now be adding the code in your question into the
UpdateFoomethod:But this relies on the assumption that
foo.Bar(with ID = 5) is valid andfoo.BarID(with ID = 4) is invalid.Generally this isn’t necessarily true, it could be just the other way around. In my opinion this snippet is a code smell which tries to fix an inconsistency in the repository layer that has actually been created in another layer (business layer or so).