Must not Entity Framework update some Fk properties automatically? Yes, he does, but sometimes not. Why?

71 views Asked by At

I have read this question and i understand that.

Let's say i have tow entities and they have One to Zero or One relatinship. Let's say I have such code:

 myFirstEntity.PrimaryKey = 5;
 myContext.Entry(myFirstEntity).State = System.Data.EntityState.Unchanged;

After the second line, myFirstEntity.MySecondEntity.PrimaryKey value will also be 5.

So, it is OK.

But, it is not wokring if make changes reversely:

 mySecondEntity.PrimaryKey = 5;
 myContext.Entry(mySecondEntity).State = System.Data.EntityState.Unchanged;

After the second line, mySecondEntity.MyFirstEntity.Pk value is still 0.

1

There are 1 answers

2
AMS On

Entity Framework will retrieve your entities from the database but will not automatically load all the properties for exemple if lazy loading is "off" (if the property is not virtual).

Also, if you change the Id of a property, you have to save the changes. With the given code, we don't know how you retrieved the entities, are they tracked ?

If the entities are not tracked, you have to manually assign the value of your FK.