无法启用延迟加载

时间:2018-06-21 09:58:14

标签: c# entity-framework

这是我的context

public class BanksContext : DbContext
{
    public BanksContext () : base("banks")
    {
        this.Configuration.LazyLoadingEnabled = true;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<History>()
           .HasRequired(t => t.Bankaccount)
           .WithMany(s => s.Histories)
           .HasForeignKey(s => s.IdBankAccount);

        modelBuilder.Entity<History>()
           .HasRequired(t => t.OperationType)
           .WithMany(s => s.Histories)
           .HasForeignKey(s => s.IdOperationType);

        modelBuilder.Entity<History>()
           .HasRequired(t => t.StatusType)
           .WithMany(s => s.Histories)
           .HasForeignKey(s => s.IdStatus);

        modelBuilder.Entity<BankAccounts>()
           .HasRequired(t => t.BankShort)
           .WithMany(s => s.BankAccounts)
           .HasForeignKey(s => s.Id_BankShort);

        modelBuilder.Entity<BankErrorLog>()
            .HasRequired(t => t.HistoryEntries)
            .WithMany(s => s.Errors)
            .HasForeignKey(s => s.IdHistory);
    }

    public DbSet<BankAccounts> BankAccounts { get; set; }
    public DbSet<BankErrorLog> BankErrorLogs { get; set; }
    public DbSet<BankShortType> BankShortTypes { get; set; }
    public DbSet<History> Histories { get; set; }
    public DbSet<OperationType> OperationTypes { get; set; }
    public DbSet<StatusType> StatusTypes { get; set; }  
}

这就是我的BankAccount模型:

public class BankAccounts
{
    [Key]
    public int Id { get; set; }
    public string Iban { get; set; }

    public virtual ICollection<History> Histories { get; set; }
}

现在我想检索数据:

private BanksContext _context = new BanksContext ();

[HttpGet]
public ActionResult Index()
{
    var firstBankAccount = _context.BankAccounts.FirstOrDefault();

    return View(bankAccounts);
}

我希望firstBankAccount.Historiesnull。由于某种原因,它不是,但是它包含来自数据库的历史数据。延迟加载似乎无法正常工作。我的问题是-为什么?

0 个答案:

没有答案