I had posted a question here yesterday with plenty of detail Database only updates after closing and opening dialog
In summary, when my child form was closed, my form with the DataGridView was supposed to reload and retrieve the latest data from the database. However, it was retrieving the PRE-Updated data instead of the POST-Updated data.
I discovered that if I changed the way I used the dbcontext when I called my GetAllByTaskId function, it will retrieve the latest data from the database. However, it seems like this only works for certain functions.
For example I have a Delete function that calls a Get function in the same class. If my Get class uses the using() dbcontext method, my delete class will not work. I believe it is because the using() method disposes of the dbcontext and so nothing is carried over to my Delete function.
How would I properly use this using() function in my case? It seems like I would need 2 methods. Also, its strange that my dbcontext wouldn't return the latest data from the database.
private AutoPrintDbContext dbContext = new AutoPrintDbContext();
public FieldsData()
{
}
public List<Field> GetAllByTaskId(string Input)
{
List<Field> data = new List<Field>();
try
{
using(AutoPrintDbContext db = new AutoPrintDbContext())
{
data = db.Fields.Where(x => x.TaskItemId == Input).ToList();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return data;
}
public Field Get(string Input)
{
Field data = new Field();
try
{
data = dbContext.Fields.SingleOrDefault(u => u.Id == Input);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return data;
}
public bool Delete(string Input)
{
try
{
var f = Get(Input);
dbContext.Fields.Remove(f);
dbContext.SaveChanges();
return true;
}
catch (Exception e)
{
Console.WriteLine(e);
return false;
}
}
This is a windows form app by the way.
usingshould be used whenever there is a database operation is happening. this would make sure to open the connection when required and close it as soon as the purpose of opening it is served. Forgetanddelete, you should dogetanddeletein one singleDbContextobject created using singleusingblock. So instead of callingGetmethod separately you should retrieve the data in the delete method itself and delete them and call SaveChanges immediately. In short you dont need class level instance ofAutoPrintDbContext.