2016-09-26 27 views
0

修改現有數據庫項目後,我無法在ListView中獲取更新項目。但是,一旦我重新加載應用程序,可以在ListView中看到更新的項目。如何刷新實體框架中的上下文

我已經綁定到一個ObservableCollectionListView

這是我的接口

public interface IService 
{ 
    IEnumerable<Employee> GetDetails(); 
    IEnumerable<Employee> GetDetailsById(int MatchID); 
} 

我已經實現IService IEmployeeServiceData類。

public class IEmployeeServiceData:IService 
{ 
    private EmployeeContext Context 
    { 
     get; 
     set; 
    } 

    public IEmployeeServiceData() 
    { 
     Context = new EmployeeContext(); 
    } 

    public IEnumerable<Model.Employee> GetDetails() 
    { 
     return Context.Employees; 
    } 

    public IEnumerable<Model.Employee> GetDetailsById(int MatchID) 
    { 
     var q = from f in Context.Employees 
       where f.EMPLOYEE_ID == MatchID 
       select f; 
     return q.AsEnumerable(); 
    } 
} 

這是我的VM

public void RefereshData() 
    { 

     var e = EmployeeService.GetDetails(); 

     if (SelectedIndexValue == 1) 
     { 
      var Data = from e1 in e 
         where e1.LOCATION == "Pune" 
         select e1; 
      EmployeeMasterData = new ObservableCollection<Model.Employee>(Data); 
     } 

     else if(SelectedIndexValue==2) 
     { 
      var Data = from e1 in e 
         where e1.LOCATION == "Bangalore" 
         select e1; 
      EmployeeMasterData = new ObservableCollection<Model.Employee>(Data); 
     } 

     else 
     { 
      EmployeeMasterData = new ObservableCollection<Model.Employee>(e); 
     } 
    } 

更新退出項目:

public void UpdateEmployee() 
    { 
     try 
     { 

      Context = new EmployeeContext(); 
      Employee Emp = Context.Employees.First(i => i.EMPLOYEE_ID == FindId1); 
      Emp.FIRST_NAME = this.FIRSTNAME; 
      Emp.FAMILY_NAME = this.FAMILY_NAME; 
      Emp.EXTERNAL_ID = this.EXTERNALID; 
      Emp.DB_SPONSOR = this.DBSPONSOR; 
      Emp.LEGAL_ENTITY = this.LEGAL_ENTITY; 
      Emp.COST_CENTER = this.COST_CENTER1; 
      Emp.STATUS = this.StatusCategory; 
      Emp.ENTRY_DATE = this.ENTRYDATE; 
      Emp.LOCATION = this.LocationCategory1; 
      Context.SaveChanges(); 
      Clear(); 
      AlertMessage1 = "Employee Record is Updated Sucessfulyy !!!"; 
      IsVisible1 = true; 
      timer.Start(); 

     } 
     catch(Exception ex) 
     { 
      Console.WriteLine(ex.InnerException); 
     } 
    } 

Existing Item

Updated Item

+0

'EmployeeMasterData'是否有通知屬性更改事件? – OmegaMan

+0

是的,我已經實現了@OmegaMan –

+0

'Employee'實現了'INotifyPropertyChanged'嗎? – OmegaMan

回答

0

的變化做一個entit實體框架中的y將不會反映在屏幕上,因爲在您的示例中,兩個實例不相關。是的,它們具有相同的值,但它們是內存中兩個不同的不同reference位置。 **對於ObservableCollection是列表的副本,而不是您的示例中正在處理的實際列表。

因此它們沒有關係。


要顯示的改變你有這些選項:

  1. 更改實際對象的財產(IES)通過觀察集合舉行鏡子做的其他變化EF實體。此外,EF實體必須遵守INotifyPropertyChange,否則數據屬性更改將不會在屏幕上顯示。
  2. 或刪除屏幕實體並將更改的實體添加到列表中。
  3. 或刪除整個可觀察列表並重新添加EF中的最新版本。 (你提到你這樣做,那也是一種選擇)。