Linq update many-many relationship
New to Linq to Entities. I am using entity framework and linq. In my db I have something akin to Cars, Users, UserCars where UserCars holds the ID from User and Cars. Standard stuff.
EF maps this to Car and User objects.
Now a user currently has many cars. Through my application I end up with a new List of Car IDs.
I need to update the UserCars table with the new list of cars for the current user.
So what needs to happen basically开发者_如何学JAVA, The current cars for the user are deleted, and the new list of car ids/userid is inserted.
What is the easiest way to go about this using linq to entities?
The User
entity should have a Cars
property. You can just clear that collection and then add the new Cars to reflect the new state, i.e. somewhat like this:
User myUser = context.Users.First();
var carCollection = context.Cars.Where( c => carIdCollection.Contains(c.Id));
myUser.Cars.Clear();
foreach(Car car in carCollection)
myUser.Cars.Add(car);
...
context.SaveChanges();
You could use a generic method which can handle what ever type you pass it:
Protected Sub UpdateManyToMany(Of T As Class)(database as SomeEntities, collection As ICollection(Of T), idList As List(Of Integer))
'update a many to many collection given a list of key IDs
collection.Clear()
Dim source = database.Set(Of T)()
If idList IsNot Nothing Then
For Each i As Integer In idList
Dim record = source.Find(i)
collection.Add(record)
Next
End If
End Sub
精彩评论