EF需要注意的virtual,懒加载,还有1对n更新
1.如果实体类型有任何一个集合属性是 virtual 的,那么该属性会懒加载,在查询该对象时,看到的类型是代理对象(proxy_xxxx), 使用new来更新1对n关系时会 增加
var order2 = dbContext.Orders.Where(x=>x.Id==6).FirstOrDefault();
//Items为virtual时,使用new会导致记录增加,如果上面加了Include("Items"),再使用new则会异常,见下文 order2.Items = new List<OrderItem>() { new OrderItem { Name="000000000" } ,new OrderItem { Name="33333333333" } };
2.如果实体类型没有集合属性是 virtual 的,那么查询出的对象是实体自身对象, 使用new更新1对n关系时会 更新
如果在懒加载结合Include时,更新1对n关系,用new的方式给集合属性赋值,则会报以下错误
var order2 = dbContext.Orders.Where(x=>x.Id==6).Include("Items").FirstOrDefault();
//当Items为virtual时,以上已经Include了,再使用下面的new则会异常 order2.Items = new List<OrderItem>() { new OrderItem { Name="777777" } ,new OrderItem { Name="999999" } };
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
正确的做法是取到集合属性,比如
order2.Items.ToList()[0].Name = "更新它";
这样就正确。