我正在使用EF 6並使用Code First定義我的數據庫。爲什麼我的實體不被延遲加載?
以下代碼行返回一個Transaction實體,但EndorsementInfo導航屬性爲null。我檢查了數據庫,確實有測試數據的數據。 「var trans」似乎具有有效的IQueryable,但導航屬性t.EndorsementInfo在它不應該爲null時爲空。
var trans = unitOfWork.GetRepository<Transaction>().GetAll().Where(t => t.PolicyId == command.PolicyId);
results.Transactions = new List<TransactionListItem>();
foreach (var t in trans)
{
results.Transactions.Add(new TransactionListItem
{
Id = t.Id,
EffDate = t.EffectiveDate,
EffectiveDate = t.EffectiveDate.ToShortDateString(),
TransactionType = t.TransactionType.ToStringValue(),
EndorsementType = t.TransactionType == TransactionType.Endorsement ?
t.EndorsementInfo.EndorsementType.Description : ""
});
}
交易實體:
public class Transaction : EntityBase
{
[Required]
public TransactionType TransactionType { get; set; }
public long PolicyId { get; set; }
public virtual Policy Policy { get; set; }
[Required]
public DateTime EffectiveDate { get; set; }
public DateTime? ExpirationDate { get; set; }
public string Description { get; set; }
public virtual Quote QuoteInfo { get; set; }
public virtual Cancellation CancellationInfo { get; set; }
public virtual NewBusiness NewBusinessInfo { get; set; }
public virtual Endorsement EndorsementInfo { get; set; }
}
簽註實體
public class Endorsement : EntityBase
{
public Transaction Transaction { get; set; }
public long EndorsementTypeId { get; set; }
public virtual EndorsementType EndorsementType { get; set; }
public int EndorsementNum { get; set; }
[MaxLength(500)]
public string EndorsementDesc { get; set; }
public Decimal? Premium { get; set; }
}
的Code First流利的配置
public class TransactionConfiguration : EntityTypeConfiguration<Transaction>
{
public TransactionConfiguration()
{
HasOptional(t => t.QuoteInfo).WithRequired(q => q.Transaction);
HasOptional(t => t.NewBusinessInfo).WithRequired(q => q.Transaction);
HasOptional(t => t.EndorsementInfo).WithRequired(q => q.Transaction);
HasOptional(t => t.CancellationInfo).WithRequired(q => q.Transaction);
}
}
庫實施GETALL
public IQueryable<T> GetAll(string include)
{
return _set.Include(include);
}
我已檢查並重新檢查一切設置是否正確。我不知道我可能會錯過什麼。
謝謝。
null異常?處置異常? – 2014-09-05 06:34:13
null foreach中的異常。 (第一個塊)唯一空的是EndorsementInfo。 – 2014-09-05 08:41:02
您將'EndorsementInfo'設置爲可選,可能代碼確實不存在於數據庫中,這意味着'Transaction'表上的'Endorsement_Id'列爲空。 – 2014-09-05 09:28:13