linq中的错误ForeignKeyReferenceAlreadyHasValueException解决方法

用Linq to sql挺长一段时间了,今天第一次碰到这个错误。
场景重现及简化:

复制代码
var user = userRepository.GetUser(userId); if (roleId > 0 ) {   user.RoleId = roleId; } else {    user.RoleId = null ; } userRepository.Save();
复制代码

这段代码普通的不能再普通,先取用户,设置角色,更新。
不过出错了。 在user.RoleId = roleId或者user.RoleId = null的位置会抛出异常 System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the obj

复制代码
        [Column(Storage = " _RoleId " , DbType = " Int " )]         public System.Nullable < int > RoleId         {             get             {                 return this ._RoleId;             }             set             {                 if (( this ._RoleId != value))                 {                     if ( this ._Role.HasLoadedOrAssignedValue)                     {                         throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();                     }                     this .OnRoleIdChanging(value);                     this .SendPropertyChanging();                     this ._RoleId = value;                     this .SendPropertyChanged( " RoleId " );                     this .OnRoleIdChanged();                 }             }         }
复制代码

我们来分析下这个错误 1. 异常抛出的位置: if (this._Role.HasLoadedOrAssignedValue) {     throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException(); }
_Role这个关联对象已经被加载出来的时候,重新设置主键RoleId不被允许。

我有加载过Role吗?想想? 在创建DataContext的位置 -_-!

DataLoadOptions loadOptions = new DataLoadOptions(); loadOptions.LoadWith < User > (it => it.Role); DataContext.LoadOptions = loadOptions;

因为希望加载用户的时候立即加载角色,所以就有了上面的代码,我并不想去掉这个,怎么办呢?只能重新取了。

复制代码
var user = userRepository.GetUser(userId); if (roleId > 0 ) {    // user.RoleId = roleId;     user.Role = roleRepository.GetRole(roleId); } else {    // user.RoleId = null;      user.Role = null ; } userRepository.Save();
复制代码

转载于:https://www.cnblogs.com/wenghaowen/p/3748129.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值