C# ObjectContext实例已被释放,不能再用于需要连接的操作。插入到表中

C# ObjectContext实例已被释放,不能再用于需要连接的操作。插入到表中,c#,orm,objectcontext,C#,Orm,Objectcontext,我正在用c#学习ORM。当我向注册表表添加注册表时,会显示错误。 我的课是 using System; using System.Collections.Generic; using System.Linq;using System.Text; namespace PreSchool { public class Child { public int ChildId {get; set;} public string Nam

我正在用c#学习ORM。当我向注册表表添加注册表时,会显示错误。 我的课是

 using System;
 using System.Collections.Generic;
 using System.Linq;using System.Text;

 namespace PreSchool

 {

    public class Child
     {

         public int ChildId {get; set;}
         public string Name { get; set; }
         public string Surname { get; set; }
         public virtual List<Register> Registers { get; set; }


         public Child()
         {          
           this.Registers = new List<Register>();
         }
     }
作用

  private void button1_Click(object sender, RoutedEventArgs e)
         {
             using (var db = new ChildContext())
             {

             Child bla= ChildrenGrid.SelectedItem as Child ;              
             var reg = new Register() {  dt_in = DateTime.Now, dt_out = DateTime.Now };          
             bla.Registers.Add(reg);     
             db.SaveChanges();
             }
         }
早些时候我遇到了一个问题,我不得不在Register类中添加“partial”来编译项目,但现在不需要了(为什么?)。主题dipslays的错误出现在这里:bla.Registers.Add(reg)


谢谢你的帮助

看起来好像您正试图将
寄存器
对象添加到已处理的上下文中。如果要将记录绑定到网格,则在检索记录时,这些记录将不再附加到数据库,您需要重新提取对象并更新该对象,例如

using (var db = new ChildContext())
{
    // get the id of the selected child
    var childId = (ChildrenGrid.SelectedItem as Child).ChildId;
    // pull that record from the "live" context
    Child entity = db.Child.Single(x => x.ChildId == childId);
    // add the new record to the "live" entity
    entity.Registers.Add(new Register
    {
        dt_in = DateTime.Now,
        dt_out = DateTime.Now
    });
    db.SaveChanges();
}

仅供参考-在UI中使用视图模型通常比实际的DB实体更好。

仅仅附加对象不更便宜(往返)吗?但是,这里的问题是实体已经传递到UI,并且可能没有保留需要附加的所有相关内部信息。就我个人而言,我觉得重新获取更安全,我无法想象开销会有这么大。
using (var db = new ChildContext())
{
    // get the id of the selected child
    var childId = (ChildrenGrid.SelectedItem as Child).ChildId;
    // pull that record from the "live" context
    Child entity = db.Child.Single(x => x.ChildId == childId);
    // add the new record to the "live" entity
    entity.Registers.Add(new Register
    {
        dt_in = DateTime.Now,
        dt_out = DateTime.Now
    });
    db.SaveChanges();
}