问题是当我从数据库获取实体并对其属性进行一些更改并想要保存更改时,我的修改 ef core 尝试不更新而是将新实体插入数据库。除此之外,数据库中已经存在具有给定 pk 的实体。我还使用存储库模式来操作访问数据库。
这是我的模型结构和代码
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);
就像你已经说过的。您尝试将已经存在的条目插入数据库中。
而不是
await _purchaseRequestDocumentRepository.InsertAsync(purchaseRequestDocument);
尝试 dbContext 的
SaveChangesAsync
方法