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 = "更新它";  

这样就正确。

 

demo地址

转载于:https://www.cnblogs.com/cabbage/p/ef-virtual-lazyload-1-to-n-update.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值