0

Simple question. I didn't have this problem using NHibernate, but now I have it with EntityFramework:

Imagine that I have a Car, with a list of Tires.

I want to remove 1 tire of a car, so I want to update it. Something like:

Car.Tires.Remove(tire);

And then I update the car object with this update method:

public virtual void Update(T obj)
{
     TryAttach(obj);
     SetAllModified(obj);
     SaveChanges();
}

The problem is that after the update, the car still have the same amount of tires.

How can I update the list of Tires when I call the update method?

alansiqueira27
  • 8,129
  • 15
  • 67
  • 111

2 Answers2

0

You need to find the tire in the database and then remove it:

var tire=context.Tires.Where(t=>t.Name==tireName).Single();
Car.Tires.Remove(tire);
context.SaveChanges();
0

Firstly, there is something a little strange about the way you have things setup... without a little more code it's hard to work out what you are doing but here is what I would expect if I was to do this myself with Entity Framework.

Firstly... you need a DbContext, your context would look something like this...

public class SomeContext : DbContext
{
    public DbSet<Car> Cars { get; set; }
    public DbSet<Tyre> Tires { get; set; }
}

Then some pocos...

public class Car {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual List<Tyre> Tires { get; set; }
}

public class Tyre {
    public virtual int Id { get; set; }

    // More properties...

    [ForeignKey("CarId")]
    public virtual int CarId { get; set; }
    public virtual Car Car { get; set; }
}

Then I would expect you to do something like this.... my brain is not working quite the same after a long day but essentially.. remove the tire you no longer need from the Car object you loaded from the database then save your changes.

using (var context = new SomeContext())
{
    var car = context.Cars.Find(carId);
    var tyre = car.Tires.Single(t => t.Id == tireId);
    car.Tires.Remove(tyre);

    context.SaveChanges();
}

Hope this helps.

BenjaminPaul
  • 2,931
  • 19
  • 18