【问题标题】:NullReferenceException with Auto-Generated Tables带有自动生成表的 NullReferenceException
【发布时间】:2013-05-08 22:34:56
【问题描述】:

我对 EF 自动生成的异常 NullReferenceException ... 类有问题,该类包含 ICollection 列表和应该在构造函数中初始化的列表,但是当尝试将项目添加到列表时,它会显示异常。

internal partial class Customer : Person
{

    partial void ObjectPropertyChanged(string propertyName);

    public Customer()
    {
        this.Accounts = new HashSet<Account>();
        this.CustomerUpdates = new HashSet<CustomerUpdate>();
    }

    public virtual ICollection<Account> Accounts { get; set; }
    public virtual ICollection<CustomerUpdate> CustomerUpdates { get; set; }
}

尝试将任何项目添加到集合时会引发异常。 "this.Accounts.Add()"

internal partial class Customer : Person, ICustomer
{
    internal Customer(Guid userId, string firstName, string surname)
        : base(userId, firstName, surname) {  }

    //List of customer accounts
    IEnumerable<IAccount> ICustomer.Accounts
    {
        get { return Accounts.AsEnumerable<IAccount>(); }
    }

    //Open SavingsAccount
    public Account OpenSavingsAccount(decimal amount)
    {
        var account = new AccountSavings();
        account.Debit(amount, "-- Opening Balance --");
        this.Accounts.Add(account);
        return account;           
    }

    //Open LoanAccount
    public Account OpenLoanAccount(decimal amount)
    {
        var account = new AccountLoan(amount);
        account.Debit(amount, "-- Opening Balance --");
        this.Accounts.Add(account);
        return account;
    }

【问题讨论】:

标签: c# entity-framework nullreferenceexception


【解决方案1】:

仅当您在查询中使用 .Include(o =&gt; o.Accounts) 时,实体框架才会初始化集合。

如果您没有该包含,则必须自己初始化列表:

if (this.Accounts == null)
    this.Accounts = new List<Account>();
this.Accounts.Add(account);

【讨论】:

  • 我认为这不是真的。当您将导航属性设为集合时,EF 会创建一个默认构造函数,将其设置为新的 HashSet,您可以在此处查看。如果您不 .Include() 它,它不会填充它,但它已初始化并且不应抛出 NullReferenceException。我认为我们没有足够的代码来发现问题所在。
  • @JeremyPridemore 同意,需要更多编码,包括使用延迟加载还是急切加载。
猜你喜欢
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
相关资源
最近更新 更多