[英]NullReferenceException with Auto-Generated Tables
我有一个由EF自动生成并包含ICollection列表和应该在构造函数中初始化的列表的Exception NullReferenceException ...类的问题,但是当尝试向列表中添加项目时,它会显示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;
}
仅当您在查询中使用.Include(o => o.Accounts)
,Entity Framework才会初始化集合。
如果没有,则必须自己初始化列表:
if (this.Accounts == null)
this.Accounts = new List<Account>();
this.Accounts.Add(account);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.