I do not understand how EF5 dbContext.Entry(entity).Reload() method is supposed to work?

若如初见. 提交于 2019-12-01 13:15:44

If dbEntities is a DbContext, then you are talking about doing, effectively dbc.Entry<ART_GRUPE>().Reload();, to discard all changes and reload the entities, not reloading your query. However, this does not exist. You can discard any changes made to a single entity using the dbc.Entry<ART_GRUPE>(myEntity).Reload() ("MSDN - DbEntityEntry<TEntity>.Reload Method").

DbContext is not meant to be long lived, you are meant to use it for your query, then get rid of it. If you want to cast it to an object context, you could try:

var ctx = ((IObjectContextAdapter)db).ObjectContext;
ctx.Refresh();

This may not be what you need. It also doesn't remove entities deleted from the db from your context, and it doesn't always refresh relationships. You may be better off getting rid of the context and loading it again:

private void GetData()
{
    // you could wrap this in a using statement, though that isn't necessary
    using (var dbc = new dbEntities())
    {
        art = from a in dbc.ARTIKLIs
            select a;

        grp = from g in dbc.ART_GRUPE
            select g;

        artikliBindingSource.DataSource = art.ToList();
        artGrupeBindingSource.DataSource = grp.ToList();
    }
}
private void refresh_Click(object sender, EventArgs e)
{
    GetData();
    // not sure you need this next line now, but you should test
    artGrupeBindingSource.ResetBindings(false); 
}

The problem this may cause you is that you are making changes to ARTIKLIs and trying to track them. For that you could use something like the following to save changes, and do not reload your ARTIKLIs each time:

private void GetData(bool loadArtikli = true)
{
    // you could wrap this in a using statement, though that isn't necessary
    using (var dbc = new dbEntities())
    {
        if (loadArtikli)
        {
            art = from a in dbc.ARTIKLIs
                select a;
        }

        grp = from g in dbc.ART_GRUPE
            select g;

        artikliBindingSource.DataSource = art.ToList();
        artGrupeBindingSource.DataSource = grp.ToList();
    }
}
private void refresh_Click(object sender, EventArgs e)
{
    GetData(false);
}

public static void UpdateARTIKLI(ARTIKLI item)
{
  using (var dbc = new dbEntities())
  {
    if (item.Id > 0)
    { // update existing ones
      var dbitem = context.ARTIKLI 
        .Find(item.Id);

      context.Entry(dbItem)
        .CurrentValues
        .SetValues(item);
    }
    else
    { // deal with new ones
      context.ARTIKLI.Add(item);
    }

    context.SaveChanges();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!