我有 2 节课:
public class FlightCostInfo : BaseEntity<Guid>
{
public Flight FlightInfo { get; set; }
public virtual ICollection<Cost> Costs { get; set; }
public virtual ICollection<PriceCalculationNotification> Notifications { get; set; }
public Guid CalculationResultId { get; set; }
}
public class Cost : BaseEntity<Guid>
{
public BasePrice Price { get; set; }
public decimal Amount { get; set; }
public Vendor Vendor { get; set; }
public Guid FlightCostInfoId { get; set; }
}
并为他们映射:
internal class FlightCostInfoMapping : EntityTypeConfiguration<FlightCostInfo>
{
public FlightCostInfoMapping()
{
HasKey(i => i.Id);
Property(i => i.CalculationResultId).HasColumnName("CalculationResult_Id");
HasOptional(i => i.FlightInfo);
HasMany(i => i.Costs).WithRequired().HasForeignKey(c => c.FlightCostInfoId);
HasMany(i => i.Notifications).WithRequired().HasForeignKey(n => n.FlightCostInfoId);
}
}
internal class CostMapping : EntityTypeConfiguration<Cost>
{
public CostMapping()
{
HasKey(c => c.Id);
Property(c => c.FlightCostInfoId).HasColumnName("FlightCostInfo_Id");
HasRequired(c => c.Price);
HasRequired(c => c.Vendor);
}
}
当我保存每个包含一个或多个 Cost 对象的 FlightCostInfo 列表时,我收到以下错误:
违反了多重性约束。角色FlightCostInfo_Costs_Source
的关系Charges.Infrastructure.DataAccess.FlightCostInfo_Costs
有多重性 1 或 0..1
我不知道为什么会这样。有人可以帮忙吗?
更新:保存 FlightCostInfo 列表的代码:
public virtual void Save(IEnumerable<TObject> entities)
{
Context.Configuration.AutoDetectChangesEnabled = false;
entities.ToList().ForEach(entity =>
{
if (Equals(entity.Id, default(TKey)) || !Context.ChangeTracker.Entries<TObject>().ToList().Any(dbEntry => dbEntry.Entity.Id.Equals(entity.Id)))
{
Set.Add(entity);
}
});
Context.ChangeTracker.DetectChanges();
SaveChanges();
Context.Configuration.AutoDetectChangesEnabled = true;
}
protected void SaveChanges()
{
var entriesWithGuidKey = Context.ChangeTracker.Entries<BaseEntity<Guid>>().Where(e => e.Entity.Id == Guid.Empty).ToList();
entriesWithGuidKey.ForEach(e => e.Entity.Id = Guid.NewGuid());
var entriesWithPeriodicValidity = Context.ChangeTracker.Entries<IPeriodicValidityObject>().ToList();
entriesWithPeriodicValidity.ForEach(e =>
{
if (e.State != System.Data.EntityState.Unchanged)
{
e.Entity.ChangedDate = DateTime.UtcNow;
}
});
Context.SaveChanges();
}