the problem is when i get my entity from database and make some changes to its properties and want to save changes my modifications ef core tryes to not update but insert new entity into database. besides this entity with given pk alredy exists in database. also i am using repository pattern to manipulate access ta database.
here is my model strucrure and code
public class PurchaseRequestDocument
{
public int DocumentId { get; set; }
public Document Document { get; set; }
public string DeliveryAddress { get; set; }
public string Description { get; set; }
public int RequestedForDepartmentId { get; set; }
public Department RequestedForDepartment { get; set; }
public int? ProjectId { get; set; }
public Project? Project { get; set; }
public ICollection<PurchaseRequestDocumentItem> Items { get; set; }
}
public class PurchaseRequestDocumentConfiguration : IEntityTypeConfiguration<PurchaseRequestDocument>
{
public void Configure(EntityTypeBuilder<PurchaseRequestDocument> builder)
{
builder.HasKey(prd => prd.DocumentId);
builder.Property(prd => prd.DocumentId)
.ValueGeneratedNever();
builder.Property(prd => prd.Description)
.HasMaxLength(4000)
.HasDefaultValue("");
builder.HasOne(prd => prd.Document)
.WithOne()
.HasForeignKey<PurchaseRequestDocument>(d => d.DocumentId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(prd => prd.RequestedForDepartment)
.WithMany()
.HasForeignKey(prd => prd.RequestedForDepartmentId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasOne(prd => prd.Project)
.WithMany()
.HasForeignKey(prd => prd.ProjectId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade);
}
}
var purchaseRequestDocument = await _purchaseRequestDocumentRepository.GetDocumentWithItems(dto.DocumentId);
if (purchaseRequestDocument is null)
throw new NotFoundException(_localizer["DocumentNotFound"]);
_mapper.Map(dto, purchaseRequestDocument);
await _purchaseRequestDocumentRepository.InsertAsync(purchaseRequestDocument);
return _mapper.Map<SavePRResponseDto>(purchaseRequestDocument);
Like you already said. You try to insert a already existing entry into your db.
Instead of
try the
SaveChangesAsyncmethod of your dbContext