为什么我的实体没有被加载?

时间:2014-09-05 01:22:09

标签: entity-framework ef-code-first

我使用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 Fluent配置

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);
}

我已经检查并重新检查了所有设置是否正确。我不知道自己可能缺少什么。

感谢。

1 个答案:

答案 0 :(得分:0)

您正在使用已打开的连接来执行两个数据读取器,您需要在连接字符串中启用多个结果集。

MultipleActiveResultSets=True;