Nyprez Nyprez - 1 month ago 6
C# Question

EF linq, delete all related OwnerId to Id

I have two tables,

car
and
owner
.
Car
-table uses
OwnerId
as FK.

I must delete cars related to
OwnerId
before I can delete that very
Owner
.

How do I point to every related row from
Car
table and delete them all togheter? As far I get error at the first line:

(It's one to many relation, many cars can have same
OwnerId
)

Car car = db.Cars.Where(c => c.OwnerId == id); //this gives me error:
db.Cars.Remove(car);
db.SaveChanges();

Owner owner = db.Owners.Find(id);
db.Owners.Remove(owner);
db.SaveChanges();


Error says:
cannot convert from System.Linq.IQueryable<X.Models.Car> to <X.Models.Car>
. How do I delete all cars related to specific
Id
?

Answer

You need first obtain all cars

List<Car> list = db.Cars.Where(c => c.OwnerId == id).ToList();

//Delete all cars
foreach(Car car in list){
    db.Cars.Remove(car);
    db.SaveChanges();
}

Owner owner = db.Owners.Find(id);
db.Owners.Remove(owner);
db.SaveChanges();
Comments