尝试引用 object 中已经存在的记录并将其添加到 EF 核心的数据库中

Trying to refer to already existing records in an object and adding it in the database in EF core

假设我们有一个 Car 实体,它与 Driver 实体具有一对多关系 我首先在数据库中创建 drivers 的记录,然后我尝试通过引用他们在数据库中注册的 ID 将它们添加到 car

Car {
    // other properties
    public ICollection<Driver> Drivers {get; set;}
}

为了使用 EF 核心实现此目的,我使用了以下简单明了的代码行

   await _context.AddAsync(carInstance) //the carInstance is passed with multiple drivers 

如果 driver 在其创建的数据库中不存在,
如果driver已经存在,则出现重复键错误

如何在不发生该错误的情况下引用 driver 中已经存在的记录?

对于现有的驱动程序记录,您需要在添加它们之前附加它们 汽车实例

_context.AttachRange(exisitngDrivers);
await _context.AddAsync(carInstance)