0

I want to refresh my database in form application but I don't know how can I. I found some code but I am not sure is it work for getting recent datas and Where should I write it.

I tried Refresh or update my datagridview but it didn't work.

public static void ReloadEntity<TEntity>(
    this DbContext context, 
    TEntity entity)
    where TEntity : class
{
    context.Entry(entity).Reload();
}
  • Where should I write this code ? Repository.cs ? RepositoryBase.cs ? AlfaPlastikContext.cs ? DbContext ? – Batuhan BAKAR Jun 18 '19 at 05:37
  • Because of it being a static method to the DbContext, this extension will be available to your class as long as your class knows where to find it ie namespace. For your main question, I would suggest to just call the routine that loads data into your datagridview to reload data. For more clarity: https://stackoverflow.com/a/16872910/1094751. – Kristianne Nerona Jun 18 '19 at 06:38

2 Answers2

1

I want to refresh my database

You dont! You are thinking about it wrong

  1. Don't cache a DbContext, meaning don't open it and keep it around indefinitely
  2. Use a using statement for short units of conceptual work. Connections are already cached under the hood and stops a lot more problems happening.
  3. Don't use repositories with EntityFramework, this is a waste of your time 99.4564564% of the time and that of future developers debugging and upgrading your code
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0
 public static void ReloadEntity<TEntity>(this DbContext context,                    TEntity entity)
             where TEntity : class
      {
         ((IObjectContextAdapter)context)
           .ObjectContext
           .Refresh(RefreshMode.StoreWins, entity);
      }