Hello. I implement a domain layer (DAL) in the project. I wrote tests for it, and I tested all the basic CRUD operations of working with the repository. One project that needs data from the DAL layer is a WPF application. I plan through autoMapper to create copies of the objects I need (in order not to make binding directly to the local EF cache). Faced with the problem of updating data.
ESSENCE OF STATION
public class Station { [Key] public int Id { get; set; } [Required(ErrorMessage = "Введите Ecp код станции")] public int EcpCode { get; set; } public string Name { get; set; } } OBTAINING DATA, CREATING COPIES, EDITING COPIES, SAVING COPIES.
var station = _unitOfWork.StationRepository.GetById(1); var copyStation = new Station { Id = station.Id, Name = "qqqq", //Поменяли значение EcpCode = station.EcpCode, Description = station.Description }; _unitOfWork.StationRepository.Update(copyStation); await _unitOfWork.SaveAsync(); REPOSITORIES
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class { protected CisDbContext Context { get; } protected DbSet<TEntity> DbSet { get; } public GenericRepository(CisDbContext context) { Context = context; DbSet = context.Set<TEntity>(); } public virtual void Update(TEntity entity) { DbSet.Attach(entity); //ИСКЛЮЧЕНИЕ!!!!!!!!! (объект с таким ID уже есть) Context.Entry(entity).State = EntityState.Modified; } public virtual void Update(TEntity entity, int pkDetached) { var existing = GetById(pkDetached); if (existing != null) Context.Entry(existing).State = EntityState.Detached; DbSet.Attach(entity); Context.Entry(entity).State = EntityState.Modified; } } When performing Update an exception is thrown.
An exception of type 'System.InvalidOperationException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: Domain.Entities. This can be what happens when you see the graph of the question. The database generated key values. In this case, it should be noted that this is the case.
To solve the problem, I added a method to the repository.
public virtual void Update(TEntity entity, int pkDetached) { var existing = GetById(pkDetached); if (existing != null) Context.Entry(existing).State = EntityState.Detached; DbSet.Attach(entity); Context.Entry(entity).State = EntityState.Modified; } Those. I detach an existing property with the same ID before the DbSet.Attach(entity) ;
In this case, it will work, but if in essence there will be references to other types (links to other tables). then the problem arises again.
Who faced with this please help)))