1

In a car sharing application a user can offer a ride and then each ride contains a list of bookings.

But when I try to add a reservation it does not work, even if the customer (which is already added) is attached...

The exception is :

Attaching an entity of type 'CARS_Models.Models.Member' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

The method is :

public void AddBooking(Booking b)
{
    using (var ctx = new DataContext(Settings.Default.db))
    {
        ctx.Members.Attach(b.Customer);
        ctx.Ride.Attach(b.Ride);

        ctx.Bookings.Add(b);

        ctx.SaveChanges();
    }
}

Everything else I did in this project works fine except this. I don't understand why this doesn't work as well.. I also tried to "Attach" after "Adding" but it doesn't work either.

Classes attributes :

public class Ride
{
    public int Id { get; set; }
    public Member Driver { get; set; }
    public int TotalSeats { get; set; }
    public DateTime Date { get; set; } = DateTime.Now;
    public String Departure { get; set; }
    public String Arrival { get; set; }
    public int Price { get; set; }
    public List<Booking> Bookings { get; set; } = new List<Bookings>();
}

public class Member
{
    public string Login { get; set; } //This is the PK
    public string Password { get; set; }
    public List<Ride> Rides { get; set; } = new List<Ride>(); //Rides that this member will drive.
    public List<Booking> Bookings { get; set; } = new List<Reservation>(); //All the bookings he made (for others ride).
}

public class Booking
{
    public int Id { get; set; }
    public Member Customer { get; set; } //The member who paid.
    public int Seats { get; set; } //Because someone can book more than 1 seat.
    public Ride Ride { get; set; } //The ride it concerns.
}
Shahzad
  • 1,315
  • 2
  • 22
  • 42
MBek
  • 155
  • 10
  • [link](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent) this Might help – Abi May 11 '17 at 10:52
  • 1
    Most likely `b.Customer` and `b.Ride.Driver` are different `Member` instances with the same PK `Login`. – Ivan Stoev May 11 '17 at 11:28
  • Oh yes, for the test I made them the same, do you think it's the problem ? I'll try with different members... – MBek May 11 '17 at 11:32
  • 1
    Omg... That was the problem... I dont know how you guessed it but thank you :D... Very impressive :p... – MBek May 11 '17 at 11:41

0 Answers0