1

我对 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;
    }
4

1 回答 1

0

如果您.Include(o => o.Accounts)在查询中使用,实体框架只会初始化集合。

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

if (this.Accounts == null)
    this.Accounts = new List<Account>();
this.Accounts.Add(account);
于 2013-05-14T15:06:05.610 回答