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

Say we have a Car entity that has a one to many relationship with a Driver entity I create records of drivers in the database first, then I try to add them to the car by referring to their Ids registered in the database.

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

to achieve this with EF core I used the straightforward following lines of code

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

If a driver doesn't already exist in the databases it's created,
If a driver already exists, an error of duplicate keys occurs

How can I refer to the already existing records of the drivers without occurrence of that error ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source