我正在使用具有代码优先方法的 Entity Framework Core。将更改保存到对其相关对象之一进行更改的实体时,我遇到了此错误:
“实体类型‘Bird’上的属性‘BirdId’是键的一部分,因此不能修改或标记为已修改。要使用标识外键更改现有实体的主体,首先删除依赖项并调用‘SaveChanges’然后将受抚养人与新委托人联系起来。”
当我将更改保存到类型实体Observation
并更新到相关Bird
对象时,我遇到了错误。我已包括以下模型设置:
public class Observation
{
[Key]
public int ObservationId { get; set; }
// other properties...
public int BirdId { get; set; }
public Bird Bird { get; set; }
}
Bird 类如下所示:
public class Bird
{
[Key]
public int BirdId { get; set; }
// other properties...
public ICollection<Observation> Observations { get; set; }
}
我完全依赖 EF Core 模型约定(我没有在OnModelCreating
方法中添加代码),它从 EF 迁移中设置数据库,如下所示:
migrationBuilder.CreateTable(
name: "Observation",
columns: table => new
{
ObservationId = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
BirdId = table.Column<int>(nullable: false),
},
constraints: table =>
{
table.PrimaryKey("PK_Observation", x => x.ObservationId);
table.ForeignKey(
name: "FK_Observation_Bird_BirdId",
column: x => x.BirdId,
principalTable: "Bird",
principalColumn: "BirdId",
onDelete: ReferentialAction.Cascade);
});
我是否正确设置了模型?
我保存更新的观察的代码如下所示:
observation.BirdId = model.Bird.BirdId;
var bird = await _birdRepository.GetBirdAsync(model.Bird.BirdId);
observation.Bird = bird;
observation.LastUpdateDate = _systemClock.GetNow;
await _unitOfWork.CompleteAsync();
但是,我认为问题在于模型中设置关系的方式。任何人都可以阐明这个问题吗?