• 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();
    复制代码
  • 相关阅读:
    大数据入门,到底要怎么学习大数据?
    大数据
    将JWT与Spring Security OAuth结合使用
    使用OAuth保护REST API并使用简单的Angular客户端
    自定义Spring Security的身份验证失败处理
    Spring Security方法级别授权使用介绍
    Nginx高并发配置思路(轻松应对1万并发量)
    Spring Security 5中的默认密码编码器
    Spring Boot Security配置教程
    Spring Security在标准登录表单中添加一个额外的字段
  • 原文地址:https://www.cnblogs.com/wenghaowen/p/3748129.html
Copyright © 2020-2023  润新知