具有自动生成表的NullReferenceException

时间:2013-05-14 15:03:35

标签: c# entity-framework nullreferenceexception

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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