这是我的主课:

public class Warehouse
{
    public List<WarehouseRelation> WarehouseRelationList { get; private set; } = new List<WarehouseRelation>();

    public void AddWarehouseRelation(
        Guid mainWarehouseId, 
        Guid relatedWarehouseId,
        int warehouseRelationProcessTypeId,
        int createUser, int langId)
    {
        WarehouseRelationList.Add(new WarehouseRelation(mainWarehouseId, relatedWarehouseId, createUser));

    }
}

这是我的关系类,它作为一个列表包含在仓库类中.

 public WarehouseRelation()
 {
      internal WarehouseRelation(Guid mainWarehouseId, Guid relatedWarehouseId, int createUser)
      {
          Id = Guid.NewGuid();
          WarehouseId = mainWarehouseId;
          RelatedWarehouseId = relatedWarehouseId;
          CreateDate = DateTime.Now;
          CreateUser = createUser;
      }
}

这就是我从数据库中获取Warehouse类的方式.Warehouse Relationship也包含在返回结果中.

public async Task PersistAsync()
 {
await _dbContext.SaveChangesAsync();
 }


public async Task<Domain.Warehouse> GetDefaultWarehouse(Guid warehouseId)
{
return await _dbContext.Warehouses.Include(x => x.WarehouseProperty)
                            .Include(x => x.WarehouseRelationList)
.FirstOrDefaultAsync(x => x.Id == warehouseId)
                                                             ;


     }

获取数据后,我将Warehouse Relation添加到Warehouse类的列表中.他们俩都有亲戚.

Warehouse warehouseInfo = _warehouseRepository.GetDefaultWarehouse();

warehouseInfo.AddWarehouseRelation(warehouseInfo.WarehouseId,relatedWarehouseId_userRepository.UserId);

_warehouseRepository.PersistAsync();

这抛出The database operation was expected to affect 1 row(s), but actually affected 0 row(s);个异常.这是正确的,因为我不更新Warehouse本身中的任何属性,但是我认为它应该将新的关系插入到关系表中.

当我判断_dbConext.ChangeTracker.Entry()以查看更改是否被跟踪时,并看到我新添加的关系状态为"已修改",但我相信它们必须被"添加"才能使EFCore持久化更改.可能正因为如此,它引发了异常.我try 更改新添加的对象状态,但它不能正常工作.

这种实施在EF核心中有效,还是在其范围之外?

推荐答案

@JonasH感谢我删除的 comments Id = Guid.NewGuid()和工作.

Csharp相关问答推荐

Plotly.NET访问互联网时出现异常

编写DataAnnotations自定义验证器的多种方法

. NET Core DB vs JSON模型设计

安装附加的. exe与Visual Studio

如何模拟耐久任务客户端在统一测试和获取错误在调度NewsListationInstanceAsync模拟设置

应用程序重新启动后,EFCore列表的BSON反序列化错误

注册所有IMediatR类

为具有实体框架后端的Reaction项目 Select 正确的Visual Studio模板

JsonSchema.Net删除假阳性判断结果

在DoubleClick上交换DataGridViewImageColumn的图像和工具提示

对于PowerShell中的ConvertTo-SecureString方法,Microsoft如何将初始化向量添加到AES加密中的安全字符串?

异步等待Foreach循环中的ConfigureAWait(FALSE)执行什么操作?

如何在同一成员上组合[JsonPropertyName]和[ObservableProperty]?

.NET8Blazor-为什么Rapzor渲染在for循环之后显示?

Visual Studio,Docker容器-容器调用:连接被拒绝

从GRPC连接创建ZipArchive

DropDownListFor未显示选定值

如何为控制器PUT操作绑定对象数组

如何更改Datagridview行标题

从具有泛型类型约束的类继承-Blazor