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

Time:05-25

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 ?

CodePudding user response:

For the existing records of drivers you need attach them before add them with carInstance

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