2013-05-14 63 views
1

我有一个异常NullReferenceException的问题...由EF自动生成并包含ICollection列表和列表应该在构造函数中初始化,但尝试添加项目到列出它显示异常。NullReferenceException与自动生成的表格

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

欢迎堆栈溢出!几乎所有的'NullReferenceException'都是一样的。请参阅“[什么是.NET一个NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)”获得一些提示。 – 2013-05-14 15:07:18

回答

0

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

如果没有包含,你将不得不自己初始化列表:

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

我不认为这是真的。当您将导航属性设为集合时,EF会创建一个默认构造函数,将其设置为一个新的HashSet,您可以在此处看到该HashSet。如果不包含'.Include()'它不会*填充它,但是它被初始化并且不应该抛出一个NullReferenceException。我认为我们没有足够的代码来发现问题出在哪里。 – 2013-05-14 15:44:43

+0

@JeremyPridemore同意,需要更多的编码,包括是否使用延迟加载或加载加载。 – 2013-05-14 17:38:08