gpt4 book ai didi

c# - Entity Framework 添加了许多实体,嵌套属性已经存在

转载 作者:行者123 更新时间:2023-11-30 22:59:04 25 4
gpt4 key购买 nike

我需要一次添加很多实体。这并不复杂:

EntityType entities = GetEntities();
dbContext.MyTable.AddRange(entities);

但是每个实体引用另一个子属性(已经存在,并且我知道它的 ID)。有没有一种有效的方法可以避免提前查询所有子属性?

for (int i = 0; i < entities.Length; i++)
{
// adding already existing property
entities[i].MyProperty = new MyProperty { Id = ExternalIds[i] };
}

dbContext.MyTable.AddRange(entities); // Don't want to create new entities

最佳答案

您可以创建仅包含 id 的空实体对象,您也可以将属性键添加到您的实体

public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}

在这里,您可以只输入 DepartmentID 值并保存,或者

Course.Department = new Department{ id = 123 }

docs says

If the reference is in the added state (in this example, the course object), the reference navigation property will not be synchronized with the key values of a new object until SaveChanges is called.

关于c# - Entity Framework 添加了许多实体,嵌套属性已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52499041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com