Reputation: 2655
I have following situation
public static void UpdateUserinfo(int id, Model model)
{
using (Entities context = new Entities())
{
userinfo userinfo = (from u in context.userinfoes where u.Id == id select u).FirstOrDefault();
userinfo.BirthDate = model.Birthdate;
var langauges = (from l in context.languages where model.LanguageIDs.Contains((int)l.LanguageID) select l);
foreach (var l in langauges)
{
userinfo.languages.Add(l);
}
context.SaveChanges();
}
}
When i try to do it like that i get an error:
{"There is already an open DataReader associated with this Connection which must be closed first."}
So basically i have a table languages and i have table userinfo and an association table userlanguages, so basically in EF you can navigate userinfo.langauges ...
My question how do i update it correctly, how do i add new languages to the userinfo then?
Or should I mabye have something like :
userinfo.languages = languages
But for that i have to give ICollection, but how to do it?
Upvotes: 1
Views: 57
Reputation: 4426
The problem is in your connection string you should add MultipleActiveResultSets=true
. Once you add this you may iterate over navigation properties on the fly.
Upvotes: 2
Reputation: 28069
Use two context objects, like so:
public static void UpdateUserinfo(int id, Model model)
{
using (Entities context = new Entities())
using (Entities context2 = new Entities())
{
userinfo userinfo = (from u in context.userinfoes where u.Id == id select u).FirstOrDefault();
userinfo.BirthDate = model.Birthdate;
var langauges = (from l in context2.languages where model.LanguageIDs.Contains((int)l.LanguageID) select l);
foreach (var l in langauges)
{
userinfo.languages.Add(l);
}
context.SaveChanges();
}
}
Upvotes: 0