我有一对多的关系,我希望在大致相同的时间存储一个和多个关系。我松散地遵循教程Apple docs。
重要的部分是我的交易(很多)和账户(一个)模型:
public class Account
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
}
public class Transaction
{
public int ID { get; set; }
public decimal Amount { get; set; }
public string Description { get; set; }
public string Note { get; set; }
public virtual Account Account { get; set; }
}
public class AccountContext : DbContext
{
public AccountContext(DbContextOptions<AccountContext> options) : base(options)
{
}
public DbSet<Transaction> Transactions { get; set; }
}
在我的初始化方法中:
public static void Initialize(AccountContext accountContext){
Account account = new Account { Name = "Checking" };
Transaction transaction = new Transaction { Amount = 120, Description = "Paycheck", Note = "First tranaction test" };
var test = account.Transactions; //To ensure it's not the access that's throwing the error
account.Transactions.Add(transaction); // <- right here
//...
}
问题:最后一行抛出&#34;对象引用未设置为对象的实例&#34;例外。
我的表正在Server Explorer中创建并且看起来正确。我试过放桌子。在我尝试的几个变体中,我尝试将帐户传递给事务构造函数:
Transaction transaction = new Transaction { Account = account, Amount = 120, Description = "Paycheck", Note = "First tranaction test" };
哪个没有帮助。