Reputation: 59
I am trying to add a list of objects and save them to the database once for all. The issue is that only the last saved Id is saved in the database! And my code goes like this:
public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)
{
var departmentCar = new DepartmentCar();
foreach (var item in carIds) {
departmentCar.CarId = item;
departmentCar.DepartmentId = DepartmentId;
departmentCar.State = ObjectState.Added;
Save(departmentCar);
}
}
Note: I'm using Repository pattern
Upvotes: 0
Views: 3128
Reputation: 35073
You are updating the same entity reference each time. Move the declaration of the new DepartmentCar inside the loop.
public void MapCarIdToDepartment(int DepartmentId, List<Guid> carIds)
{
foreach (var item in carIds)
{
var departmentCar = new DepartmentCar
{
CarId = item,
DepartmentId = DepartmentId
};
Save(departmentCar);
}
}
Ideally though all you should be doing is creating a new car, adding it to the DbContext's Cars DbSet, then after that is done, call SaveChanges on the context at the end. Though for the IDs if it's possible to get existing cars, you will need to check the context for that existing object to update vs. creating a new one.
public void MapCarIdToDepartment(int departmentId, List<Guid> carIds)
{
using (var context = new CarContext())
{
foreach (var carId in carIds)
{
var car = context.DepartmentCars.SingleOrDefault(x => x.CarId == carId);
if (car == null)
{
car = new DepartmentCar{ CarId = carId };
context.DepartmentCars.Add(car);
}
car.DepartmentId = departmentId;
}
context.SaveChanges();
}
}
This will check for an existing car, update it if necessary, or create a new one and update. If creating an entity is fairly involved then create a factory method such as "createCar(carId, [+other required values/references])" to keep the code easy to follow.
From here consider dependency injection or a unit of work for the DbContext rather than newing up a context in the method/class. DbContexts are a powerful tool which you can leverage so I don't recommend trying to hide them behind traditional CRUD wrapper interfaces. (Get(), Save(), etc.)
Upvotes: 2