zoukankan      html  css  js  c++  java
  • 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();
    复制代码
  • 相关阅读:
    C++类中的封装-9
    递归神经网络
    卷积神经网络
    Tensorflow人工智能神经网络学习
    右键弹出菜单 并动态新增菜单子项
    sql 列转行
    sql 删除表中某字段的重复数据
    疑难问题解决
    jquery ashx交互 返回list 循环json输入信息
    jquery 控件赋值
  • 原文地址:https://www.cnblogs.com/wenghaowen/p/3748129.html
Copyright © 2011-2022 走看看