Entity Framework Many-to-Many relastionship update with detached entities
I'm trying to update a detached entity's relationship. Say, I've got
CarTypes table and Salesmen table. A salesmen can sell more then one type
of car and one type of car can be sold by more then one salesman. DB has a
linking table between CarTypes and Salesmen but EF generated only two
Entities. I'm trying to update some CarType properties as well as the
relationship to the Salesmen entity to redefine who can sell this car
type. A Salesman entity should stay unchanged. My CarType is defined
something like this
class CarType
{
Id {get;set;}
Name {get;set;}
.....
ICollection<Salesman> Salesmen {get;set;}
}
I attach the object like this:
db.CarTypes.Attch(carTypeToUpdate);
Mark each relevant property of carTypeToUpdate as modified like this:
db.Entry(carTypesToUpdte).Property("propertyName").IsModified = true;
and finally do
db.SaveChanges();
Everything is OK with normal properties. However, I can't figure out how
to update the relationships. I've tried to attach the Salesman object and
then do
db.Entry(carTypeToUpdate).Collection("Salesmen").CurrentValue =
myUpdatedList;
However, then objects defined in the list are added to the relationship,
but the old once are not removed. I was hoping then when you set
CurrentValue, it will override all entries. No such luck!
Please help!...
No comments:
Post a Comment