1

I have a problem with the Exception NullReferenceException ... class that auto generated by EF and contains a list of ICollection and the list supposed to be initialized in the constructor but when trying to add items to the list it shows the 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; }
}

The Exception is thrown when trying to add any item to the collection. "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;
    }
Yuck
  • 49,664
  • 13
  • 105
  • 135
mario.89
  • 11
  • 1
  • Welcome to Stack Overflow! Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 14 '13 at 15:07

1 Answers1

0

Entity Framework only initializes the collections if you use .Include(o => o.Accounts) in your query.

If you do not have that include you will have to initialize the list yourself:

if (this.Accounts == null)
    this.Accounts = new List<Account>();
this.Accounts.Add(account);
Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • 1
    I don't think that's true. When you make a navigation property a collection, EF creates a default constructor that sets it to a new HashSet, which you can see here. It doesn't *populate* it if you don't `.Include()` it, but it is initialized and shouldn't throw a NullReferenceException. I don't think we have enough code to spot where the problem is here. – Jeremy Pridemore May 14 '13 at 15:44
  • @JeremyPridemore agreed, more coding is needed, including whether lazy loading or eager loading is used. – Nick Patsaris May 14 '13 at 17:38