0

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

4
  • 1
    So you are passing newItem to the Save method and there seem to be nothing names newItem in the code you shared. Should that de departmentCar? Commented Mar 21, 2019 at 10:42
  • add details, provide a definition of the Save method. is it contain context.savechanges()? Commented Mar 21, 2019 at 10:51
  • @shahzad it was by mistake, i edited it. Commented Mar 21, 2019 at 12:38
  • @TanvirArjel The save method is fine don't worry! the answer below by Steve was more than enough! Thank you guys. Commented Mar 21, 2019 at 12:39

1 Answer 1

2

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Steve! such great advices and i totally agree but i'm forced to work that way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.