1
我有2類:實體框架4.3:多重約束違反
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);
}
}
當我節省FlightCostInfo的List,每個包含一個或更多成本對象我收到以下錯誤:
違反了多重性約束。關係Charges.Infrastructure.DataAccess.FlightCostInfo_Costs
的作用FlightCostInfo_Costs_Source
有重複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();
}
你可以發佈你正在使用用於創建和保存'FlightCostInfo'列表中的代碼? – greg84
@ greg84請參閱我的更新。 –
對不起,我的意思是創建'FlightCostInfo'列表的代碼並向其添加了'Cost'實體... – greg84