I do not understand how EF5 dbContext.Entry(entity).Reload() method is supposed to work?
在这个例子中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | using System; using System.Collections.Generic; using dbModel; using System.Linq; using System.Data.Entity.Infrastructure; namespace WinApp { public partial class Form1 : Form { private dbEntities dbc; public IQueryable<ARTIKLI> art; public IQueryable<ART_GRUPE> grp; public Form1() { InitializeComponent(); dbc = new dbEntities(); } private void GetData() { 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 Form1_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) { dbc.SaveChanges(); } private void loadData_Click(object sender, EventArgs e) { this.GetData(); } private void refresh_Click(object sender, EventArgs e) { dbc.Entry(grp).Reload(); artGrupeBindingSource.ResetBindings(false); } } } |
一切顺利。 但是当我运行并单击"刷新"按钮时,出现错误:
The entity type DbQuery`1 is not part of the model for the current context
我只是尝试使用
有人可以在上面的代码中解释我的错误吗?
如果
1 2 | var ctx = ((IObjectContextAdapter)db).ObjectContext; ctx.Refresh(); |
这可能不是您所需要的。 它也不会从您的上下文中删除从数据库中删除的实体,并且它并不总是刷新关系。 您最好摆脱上下文并重新加载它:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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); } |
这可能导致您的问题是您正在对
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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(); } } |