Search code examples
c#linqentity-framework-core

The database operation was expected to affect 1 row(s), but actually affected 0 row(s); after _dbContext.SaveChanges();


This is my main class:

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));

    }
}

This my relation class,which is included as a list in Warehouse class.

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

This is how I fetch the Warehouse class from database. WarehouseRelations are included in the returned result as well.

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)
                                                             ;


     }

After fetching the data, I am adding WarehouseRelation to the list in the Warehouse class. They both have relation.

Warehouse warehouseInfo = _warehouseRepository.GetDefaultWarehouse();

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

_warehouseRepository.PersistAsync();

This throws The database operation was expected to affect 1 row(s), but actually affected 0 row(s); exception. It is correct because I don't update any properties in the Warehouse itself, however I believe it should insert the new relations to the relation table.

When I check the _dbContext.ChangeTracker.Entries() to see if the change is tracked and see my new added relation state as "Modified" but I believe they must be "ADDED" for EFCore to persist changes. Probably because of that it is throwing exception.I try to change my new added object state but it does not work properly.

Does this kind of implementation work in the EF Core, or is it outside of its scope?


Solution

  • @JonasH tenks for comment I delete to Id = Guid.NewGuid() and work.