Reputation: 7521
I've made simple database with 2 tables and few columns in each. In some tutorial I read when I install entity framework 4.1+ I can generate "DbContext code" and then I can use Local context to get ObservableCollection, which is better than DbSet, because it's automatically updating UI. So I installed entity framework 4.1, selected my database model and chose "ADO.NET DbContext Generator". So I got this:
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; }
}
}
plus StudModel.tt file with simple table models.
So in main class I added this:
DatabaseEntities db = new DatabaseEntities();
But then I realized that db.Students.Local is empty (I manually added 2 records in editor before), although db.Students has 2 records. So I found this: ObservableCollection better than ObjectSet (second answer), but there's no such method "Load". What am I missing? Should I add some special code to get this "Load" working?
I just simple wanted to: 1. Make new project and add simple database. 2. Automatically generate some code using Entity Framework so I can just bind table to DataGrid or something, which is automatically updated when data is changed (so I need ObservableCollection). 3. When I have this add some functions to Insert/Update/Delete data (with autoupdate ofc).
Please help, cheers ;)
Upvotes: 1
Views: 1930
Reputation: 127
There will be nothing in Local until you execute a query against the database. One way to accomplish this is to call Load, which does so, and returns an ObservableCollection(Of Student) (in your case).
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
Or I guess you can go this route:
Dim bs = New BindingSource
db.Students.Load
bs.DataSource = db.Students.Local.ToBindingList
Sorry, C# is not my friend. The above code should convert easily.
The steps you took above to generate the model and context look fine.
Upvotes: 1