当我加载数据时,所有内容都已正确映射和加载,但是当我尝试使用 插入对象图时Period
,PaymentType
它CalendarEntry
会引发异常:
{"Cannot insert the value NULL into column 'PaymentTypeId', table 'CashFlowCalculator.dbo.CalendarEntries'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
原因是尝试插入的对象的外键列没有值。我不知道映射中的错误在哪里?
对象
public class Period
{
public virtual int Id { get; private set; }
public virtual DateTime StartDate { get; set; }
public virtual DateTime EndDate { get; set; }
public virtual double OpeningCash { get; set; }
public virtual IList<CalendarEntry> CalendarEntries { get; set; }
public Period()
{
CalendarEntries = new List<CalendarEntry>();
}
}
public class PaymentType
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual DateTime StartDate { get; set; }
public virtual DateTime EndDate { get; set; }
public virtual bool IsIncome { get; set; }
public virtual IList<CalendarEntry> CalendarEntries { get; set; }
public PaymentType()
{
CalendarEntries = new List<CalendarEntry>();
}
}
public class CalendarEntry
{
public virtual int Id { get; private set; }
public virtual double Amount { get; set; }
public virtual DateTime DueDate { get; set; }
public virtual PaymentType PaymentType { get; set; }
public virtual Period Period { get; set; }
public CalendarEntry(){ }
public virtual void AddPaymentType(PaymentType paymentType)
{
paymentType.CalendarEntries.Add(this);
PaymentType = paymentType;
}
public virtual void AddPeriod(Period period)
{
period.CalendarEntries.Add(this);
Period = period;
}
}
映射
public PeriodMap()
{
Table("Periods");
Id(x => x.Id);
Map(x => x.OpeningCash);
Map(x => x.StartDate);
Map(x => x.EndDate);
HasMany(x => x.CalendarEntries).LazyLoad().Inverse().Cascade.All();
}
public PaymentTypeMap()
{
Table("PaymentTypes");
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.Description);
Map(x => x.StartDate);
Map(x => x.EndDate);
Map(x => x.IsIncome);
HasMany(x => x.CalendarEntries).LazyLoad().Inverse().Cascade.All();
}
public CalendarEntryMap()
{
Table("CalendarEntries");
Id(x => x.Id);
Map(x => x.Amount);
Map(x => x.DueDate);
References(x => x.PaymentType).Column("PaymentTypeId");
References(x => x.Period).Column("PeriodId");
}