Dear StackOverflow community,
I have a problem to update a many-to-many relationship in EF 3.5:
But first of all, here you can see my Tables:
Table "Message":
ID, int (primary key)
Message, string
Table "DisplayDestinations":
ID, int (primary key)
Destination, string
My DisplayDestinations are:
ID;Destination:
1;PC
2;Mobile
3;Printer
4;PDF
I think you can imagine that a "Message" can have multiple DisplayDestinations.
I can insert and delete "Messages" or single "DisplayDestinations". But if I want to update them, I get an error.
EF 3.5 want to create a new "DisplayDestinations" but I don't have any line of code to do this...
Here is my update method. It could be solved inconveniently but why can't I update this:
List<DisplayDestinations> CorrectMDfromMDs = new List<DisplayDestinations>(); // Holds the real DisplayDestinations with the right ID and Destination
foreach (Message item in Messages)
{
// Get all DisplayDestinations with the EntityState Added or Modified to know which to add.
var ChangedMDs = item.DisplayDestinations.Where(x => x.EntityState == System.Data.EntityState.Added || x.EntityState == System.Data.EntityState.Modified);
foreach (MD md in ChangedMDs)
{
CorrectMDfromMDs.Add(DBService.GetMDs().FirstOrDefault(x => x.ID == md.ID));
}
// delete the DisplayDestinations from the Message which modified or added state, because they aren't the right from my DisplayDestinations
while (ChangedMDs.Count() > 0)
{
item.MDs.Remove(ChangedMDs.ElementAt(0));
}
// Add the right DisplayDestinations to the Message
foreach (var md in CorrectMDfromMDs)
{
item.MDs.Add(md);
}
CorrectMDfromMDs.Clear();
}
DBService.SaveChanges();
After that, I get an exception that Destination from DisplayDestinations cannot be NULL. I think EF 3.5 tries to add an new DisplayDestination into DisplayDestinations but why?
I have tried this Insert/Update Many to Many Entity Framework . How do I do it? but without success.
Thank you in advance!