我有以下情况
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();
}
}
当我尝试这样做时,我得到一个错误:
{“已经有一个与此Connection关联的开放DataReader 必须先关闭。“}
所以基本上我有一个表语言,我有表userinfo和一个关联表userlanguages,所以基本上在EF你可以导航userinfo.langauges ...
我的问题如何正确更新,如何将新语言添加到userinfo呢?
或者我应该有类似的事情:
userinfo.languages = languages
但是为了那个我必须给ICollection,但是怎么做呢?
答案 0 :(得分:2)
问题在于您应该添加MultipleActiveResultSets=true
的连接字符串。添加后,您可以动态迭代导航属性。
答案 1 :(得分:0)
使用两个上下文对象,如下所示:
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();
}
}