Jeffrey Zhang
Jeffrey Zhang

Reputation: 438

How to replace the foreign key entity use Entity Framework?

I'm use Entity Framework code first in my project. I have two entiy has one to multi relation:

public class Car
{
    public Guid ID { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
}

public class CarMapping
{
    public Guid ID { get; set; }
    public virtual Car Car { get; set; } 
}

And now I have get a carID and want to replace the car in CarMapping. I try to this:

var carMapping = DbContext.CarMappings.SingleOrDefault(m => m.ID == id);
carMapping.Car.ID = carID;

But it will lead to EF update Car and throw a exception said primary key cannot be change.

Upvotes: 0

Views: 215

Answers (1)

opewix
opewix

Reputation: 5083

Calling carMapping.Car property will return you Car object. So you cannot change primary key in Car object.

If you want to change Car in CarMapping you should do next:

Car car = DbContext.Cars.Single(r=>r.ID == carID);
CarMapping carMapping = DbContext.CarMappings.SingleOrDefault(m => m.ID == id);
carMapping.Car = car;
DbContext.SaveChanges();

Upvotes: 2

Related Questions