这是我的主课:
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核心中有效,还是在其范围之外?