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            {                 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();
复制代码
posted @ 2014-05-23 17:13  天殇月痕  阅读(300)  评论(0编辑  收藏  举报