用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 { returnthis._RoleId; } set { if ((this._RoleId != value)) { if (this._Role.HasLoadedOrAssignedValue) { thrownew 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();