I wanna connect to a Sqlite database with EF Core and followed this tutorial(https://learn.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite).
All works well(including insert/delete/update and so on).
There is a DbContext
:
public Database.ProductDbContext PDC = new Database.ProductDbContext();
And also I want to bind the dbset
PDC.StoreIn
to a ItemsControl
.
I tried bind it like this but it did not work at all:
It reports an error:
System.Windows.Data Error: 40 : BindingExpression path error: 'PDC+StoreIn' property not found on 'object' ''SelectProduct' (Name='')'. BindingExpression:Path=PDC+StoreIn; DataItem='SelectProduct' (Name=''); target element is 'CollectionViewSource' (HashCode=8674443); target property is 'Source' (type 'Object')
However, if I convert it to a ObservableCollection
and bind it, it works. Just like this:
public ObservableCollection OC = new ObservableCollection<Database.StoreIn>(PDC.StoreIn);
<ItemsControl ItemsSource="{Binding OC">
</ItemsControl>
Whereas, as we know, whenever the database insert/update/delete, the ObservableCollection
will not update so I have to bind the database directly.
How can I bind the dbset
? Thank you.
====================================================
Finally I found another solution more easily but not the answer of duplicate one.
public ObservableCollection<Database.StoreIn> OC
{
get {
return new ObservableCollection<Database.StoreIn>(PDC.StoreIn);
}
}
Just bind the OC.
Whenever you insert/update/delete the database, for example:
PDC.StoreIn.Local.Add(new Database.StoreIn());
PDC.SaveChanges();
OnPropertyChanged("OC");
Use a INotifyPropertyChanged
, then the UI will changes while you change the database now.