简体   繁体   English

我是否需要使用EntityFramework更新一对多关系中的两个实体?

[英]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 ? 如果要使用已存储在DatabaseAccount对象向DbContext.Expenses添加新的Expense ,是否还需要将新的Expense添加到该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. 在我的测试中,如果我只是创建一个新的Expense实体,则无法从Account Model访问关联的Expenses

Do the following: 请执行下列操作:

  • Add new Expense to the expenses collection 将新Expense添加到费用收集
  • On the already existing Account entity set the Expense property to be the new entity created. 在已经存在的Account实体上,将Expense属性设置为创建的新实体。
  • Save changes. 保存更改。

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

相关问题 使用一对多关系实体列表的属性更新db上的实体 - Update entity on db with a property of list of entities with one-to-many relationship 删除一对多关系中的相关实体 - deleting related entities in a one-to-many relationship EntityFramework:将现有的一对多关系映射到模型 - EntityFramework : Mapping existing one-to-many relationship to Model 不记得之前为一对多关系添加的实体的实体列表 - List of entities not remembering previously added entities for a one-to-many relationship 在EntityFramework中,如何重新加载多对多关系中的实体? - In EntityFramework how do you reload entities in a Many to Many relationship? 如何使用SauceDB将一对多关系转换为列表属性? - How do I turn a one-to-many relationship into a list property using SauceDB? 如何使用 Entity Framework Core 建立一对多关系? - How do I set up a one-to-many relationship using Entity Framework Core? EntityFramework中的一对多 - Double one-to-many in EntityFramework EF 7:如何以一对多关系加载相关实体 - EF 7: How to load related entities in a One-to-many relationship ASP.Net Core:如何更新(更改/添加/删除)嵌套项对象(一对多关系)? - ASP.Net Core: How do I update (change/add/remove) nested item objects (One-to-Many relationship)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM