ahmedpio
ahmedpio

Reputation: 142

C# How can i use Entity Framework Entities with ObservableCollection

when i tried that

using (var db = new NewDbContext())
{
    var AllItems = new ObservableCollection<db.Items>();
    ItemsDataGrid.ItemsSource = AllItems;
}

i got that error

'db' is a variable but is used like a type

Upvotes: 0

Views: 1708

Answers (3)

JOpolka
JOpolka

Reputation: 121

For anyone coming across this issue. You can also directly use:

ObservableCollection<Item> AllItems = db.Items.Local;

To populate the collection you might need to call db.Items.Load(), which is an extension from System.Data.Entity

Upvotes: 0

Peter Bons
Peter Bons

Reputation: 29800

That is because db.Items is not a Type but a collection of a certain type (I suppose that type is Item?) .

So try this:

    var AllItems = new ObservableCollection<Item>(db.Items);
    ItemsDataGrid.ItemsSource = AllItems;

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

db.Items will return a collection of type IQueryable<Item>. It looks like you want to convert the result of IQueryable<T> to ObservableCollection<T>.

You actually need to pass the Items in the constructor of Observable. The correct code would be :

ObservableCollection<Item> AllItems = new ObservableCollection<Item>(db.Items);

and then:

ItemsDataGrid.ItemsSource = AllItems;

Hope it helps.

Upvotes: 1

Related Questions