简体   繁体   English

实体框架是否不能自动更新某些Fk属性? 是的,他有,但有时没有。 为什么?

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

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. 在第二行之后, myFirstEntity.MySecondEntity.PrimaryKey值也将为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. 在第二行之后, mySecondEntity.MyFirstEntity.Pk值仍为0。

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. 另外,如果您更改属性的ID,则必须保存更改。 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. 如果未跟踪实体,则必须手动分配FK的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM