我在 .NET6 中有一个项目,其中我有一个域实体/AggregateRoot (ScoreCard),它具有添加更多子实体 (ScoreCardIndicator) 的方法,它是一个导航属性,也是一个实体。下面是我如何将 ScoreCardIndicators 添加到域模型上的记分卡的片段;
public void AddScoreIndicators(List<ScoreIndicatorId> scoreIndicatorIds,
List<ScoreCardPointsMetricData> scoreCardPointsMetricData)
{
// some code omitted for brevity
foreach (var scoreIndicatorId in scoreIndicatorIds)
{
// omitted for brevity
var scoreGrid = scoreCardPointsMetricData.FirstOrDefault(x => x.ScoreIndicatorId == scoreIndicatorId.Value)
.IndicatorMetrics
.Select(x => new ScoreGridData(x.ScoreIndicatorOptionId, (float?)x.MinValue, (float?)x.MaxValue, x.Point))
.ToList();
_scoreCardIndicators.Add(ScoreCardIndicator.Create(scoreIndicatorId, Id, scoreGrid));
}
_dateUpdated = DateTime.Now;
}
但是调用SaveChanges()时,抛出如下异常
数据库操作预计会影响 1 行,但实际上 受影响的 0 行;数据可能已被修改或删除,因为 实体被加载。看 http://go.microsoft.com/fwlink/?LinkId=527962 有关信息 理解和处理乐观并发异常。
我知道错误是因为添加了新实体,但它只是一个连接表,它是 ScoreCard 和 ScoreIndicator 实体之间多对多关系的结果。即使我将 ScoreCard 实体标记为已修改,EF 仍然不会让它成功保存。我真的需要知道我错过了什么。
有关更多信息,我在 EF-core 中使用代码优先方法。上述实体的实体映射配置如下
public void Configure(EntityTypeBuilder<ScoreCard> builder)
{
builder.ToTable("ScoreCards");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).HasColumnName("ID");
builder.Property<string>("_name").HasColumnName("Name");
builder.Property<string>("_description").HasColumnName("Description");
builder.Property<string>("_institutionCode").HasColumnName("InstitutionCode");
builder.Property<DateTime>("_dateCreated").HasColumnName("DateCreated");
builder.Property<DateTime?>("_dateUpdated").HasColumnName("DateUpdated");
builder.OwnsMany<ScoreCardIndicator>("_scoreCardIndicators", x =>
{
x.WithOwner().HasForeignKey("ScoreCardId");
x.ToTable("ScoreCardIndicators");
x.HasKey("ScoreIndicatorId", "ScoreCardId");
x.Property<ScoreIndicatorId>("ScoreIndicatorId");
x.Property<ScoreCardId>("ScoreCardId");
x.OwnsMany<ScoreGrid>("_scoreCardMetrics", x =>
{
x.WithOwner().HasForeignKey("ScoreIndicatorId", "ScoreCardId");
x.ToTable("ScoreCardGrid");
x.HasKey(x => x.Id);
x.Property(x => x.Id).HasColumnName("ID");
x.Property<ScoreIndicatorId>("ScoreIndicatorId");
x.Property<ScoreCardId>("ScoreCardId");
x.Property<ScoreIndicatorOptionId>("ScoreIndicatorOptionId").IsRequired(false);
x.Property("_minValue").HasColumnName("MinValue");
x.Property("_maxValue").HasColumnName("MaxValue");
x.Property("_points").HasColumnName("Points");
x.Property("_dateCreated").HasColumnName("DateCreated");
});
});
}