The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. Insert to table

StackOverflow https://stackoverflow.com/questions/18867426

  •  29-06-2022
  •  | 
  •  

Question

im learning ORM in c#. When I`m adding register to Register table the error is displayed. My classes are.

 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>();
         }
     }

AND

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

 namespace PreSchool
 {
     public  class Register //partial
     {

         public int RegisterId { get; set; }
         public DateTime dt_in { get; set; }
         public DateTime dt_out { get; set; }
         public virtual Child Child { get; set; } 
     }
 }

Function

  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();
             }
         }

Earlier I had a problem and I had to add "partial" in Register Class to compile the project but now its not necesarry ( why?). The error from subject dipslays in this place : bla.Registers.Add(reg);

Thanks for any help !

Était-ce utile?

La solution

It appears as though you are trying to add the Register object to a disposed context. If you are binding records to a grid then they will no longer be attached to the DB when you retrieve them, you need to re-pull the object and update that instead e.g.

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();
}

FYI - it's generally a better idea to use view models for your UI rather than actual DB entities.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top