簡體   English   中英

NullReferenceException與自動生成的表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM