2012-07-16 102 views
1

我已經做了簡單的數據庫,每個表中有兩個表格和幾列。在一些教程中,當我安裝實體框架4.1+時,我可以生成「DbContext代碼」,然後使用Local context獲取ObservableCollection,它比DbSet更好,因爲它會自動更新UI。所以我安裝了實體框架4.1,選擇了我的數據庫模型並選擇了「ADO.NET DbContext Generator」。所以我得到了這個:如何使用實體框架從數據庫生成可用的dbcontext?

namespace BazaStudentow 
{ 
    using System; 
    using System.Data.Entity; 
    using System.Data.Entity.Infrastructure; 

    public partial class DatabaseEntities : DbContext 
    { 
     public DatabaseEntities() 
      : base("name=DatabaseEntities") 
     { 
     } 

     protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 
      throw new UnintentionalCodeFirstException(); 
     } 

     public DbSet<Notes> Notes { get; set; } 
     public DbSet<Students> Students { get; set; } 
    } 
} 

加上StudModel.tt文件與簡單的表模型。因此,在主類

我加了這一點: DatabaseEntities db = new DatabaseEntities();

但後來我意識到,db.Students.Local是空的(我手動添加2條記錄編輯器之前),雖然db.Students有2條記錄。所以我發現這個:ObservableCollection better than ObjectSet(第二個答案),但沒有這樣的方法「加載」。我錯過了什麼?我應該添加一些特殊的代碼來獲得這個「負載」工作?

我只是簡單想要: 1.新建項目並添加簡單的數據庫。 2.使用實體框架自動生成一些代碼,這樣我就可以將表綁定到DataGrid或其他東西,當數據發生更改時會自動更新(所以我需要ObservableCollection)。 3.當我有這個添加一些功能插入/更新/刪除數據(自動更新ofc)。

請幫幫忙, 歡呼;)

回答

1

將有沒有在本地,直到你對數據庫執行查詢。實現這一點的一種方法是調用Load,這樣做,並返回ObservableCollection(Of Student)(在你的情況下)。

Dim bs = New BindingSource 
Dim s = db.Students 

s.Load() 

'At this point, Local will contain all students. 
'Cast to a BindingList, which stays in sync with the ObservableCollection. 

bs.DataSource = s.Local.ToBindingList 

或者我想你可以走這條路線:

Dim bs = New BindingSource 
db.Students.Load 
bs.DataSource = db.Students.Local.ToBindingList 

對不起,C#是不是我的朋友。上面的代碼應該很容易轉換。

您在上面用於生成模型和上下文的步驟看起來很好。

相關問題