简体   繁体   English

NullReferenceException与自动生成的表

[英]NullReferenceException with Auto-Generated Tables

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. 我有一个由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; }
}

The Exception is thrown when trying to add any item to the collection. 尝试向集合中添加任何项目时抛出该异常。 "this.Accounts.Add()" “ 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;
    }

Entity Framework only initializes the collections if you use .Include(o => o.Accounts) in your query. 仅当您在查询中使用.Include(o => o.Accounts) ,Entity Framework才会初始化集合。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM