c# - Entity Framework Context.Set<T>().Local would not sync with Datagrid after calling LoadAsync -
entity framework local property observablecollection , can bind lets datagrid. items not update call loadasync, or update not reflect datagrid. consider following example:
xaml
<grid> <grid.rowdefinitions> <rowdefinition height="auto" /> <rowdefinition /> </grid.rowdefinitions> <stackpanel orientation="horizontal"> <button content="load" click="btnload_click"/> <button content="loadasync" click="btnloadasync_click"/> <button content="setdatasource" click="btnsetdatasource_click"/> </stackpanel> <datagrid name="grdtest" grid.row="1"/> </grid>
code behind
testcontext db = new testcontext(); public mainwindow() { initializecomponent(); } private void window_loaded(object sender, routedeventargs e) { grdtest.itemssource = db.suppliers.local; } private void btnload_click(object sender, routedeventargs e) { var beforquery = db.suppliers.local; db.suppliers.load(); } private void btnloadasync_click(object sender, routedeventargs e) { var beforquery = db.suppliers.local; db.suppliers.loadasync(); } private void btnsetdatasource_click(object sender, routedeventargs e) { grdtest.itemssource = null; grdtest.itemssource = db.suppliers.local; }
if press load button first, behave expected (load items collection , reflected datagrid)
if press loadasync button first, 1 item loaded local items (which question, why 1 item), not reflected datagrid, can press setdatasource see that.
each time press loadasync 1 item added previous set!!
and if press loadasync , load error come , "an itemscontrol inconsistent items source"
now question is, how can use loadasync , local items properly? if can not load items form database loadasync method, use?
the problem itemssource
being updated on different thread control's thread. if you're using .net 4.5, can use enablecollectionsynchronization
allow multiple threads access collection.
see this answer example.
Comments
Post a Comment