简体   繁体   中英

Do I need to update both Entities in a one-to-many relationship using EntityFramework?

I have two Entities which look like this:

public class Account
{
    public int AccountId { get; set; }
    public string AccountName { get; set; }
    public decimal AccountBalance { get; set; }

    public virtual Expense Expense { get; set;} 
}

public class Expense
{
    public int ExpenseId { get; set; }
    public string ExpenseName { get; set; }
    public decimal ExpenseAmount { get; set; }

    public virtual ICollection Accounts { get; }
}

If I want to add a new Expense to the DbContext.Expenses with an Account object that is already stored within the Database , do I also need to add this new Expense to that Account Entity ?

In my testing there was no way to access the associated Expenses from the Account Model if I simply create a new Expense entity.

Do the following:

  • Add new Expense to the expenses collection
  • On the already existing Account entity set the Expense property to be the new entity created.
  • Save changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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