Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Binding EntityFramework to DataGrid

$
0
0

So, I've tried to fix this for few hours already, googled everything I could and nothing seems to work (using EF 6)

[Table("Customers")]
public class Customer
{
    public Customer()
    {
        this.Customers = new ObservableCollection<Customer>();
    }

    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string City { get; set; }
    public virtual ObservableCollection<Customer> Customers { get; set; }
}

Context:

classContext:DbContext{publicContext():base("name=Customers"){Database.SetInitializer<Context>(newDropCreateDatabaseIfModelChanges<Context>());}publicDbSet<Customer>Customers{ get;set;}protectedoverridevoidOnModelCreating(DbModelBuilder modelBuilder){base.OnModelCreating(modelBuilder);}}

Then I implement ObservableObject class, which implements INotifyPropertyChanged

publicclassObservableObject:INotifyPropertyChanged{publiceventPropertyChangedEventHandlerPropertyChanged;protectedvoidRaisePropertyChanged(string _propertyName){if(PropertyChanged!=null){PropertyChanged(this,newPropertyChangedEventArgs(_propertyName));}}}

Then there is CustomerViewModel, which loads all Customers and raise RaisePropertyChanged

publicclassCustomerViewModel:ObservableObject{Context ctx =newContext();privateCustomer customer =newCustomer();ObservableCollection<Customer> customers =newObservableCollection<Customer>();publicObservableCollection<Customer>Customers{
        get{return customer.Customers;}set{if(customer.Customers!= value){
                customer.Customers= value;base.RaisePropertyChanged("Customers");}}}publicstringCustomerName{
        get{return customer.CustomerName;}set{if(customer.CustomerName!= value){
                customer.CustomerName= value;base.RaisePropertyChanged("CustomerName");}}}publicObservableCollection<customer> getAllCustomers(){
        ctx.Customer.Load();
        customer.Customer= ctx.Customer.Local;return customer.Customer;}}

Then in MainWindow_Loaded I bind viewModel to DataGrid

privatevoidMain_Loaded(object sender,RoutedEventArgs e){try{CustomerViewModel viewModel =newCustomerViewModel();DataGrid1.DataContext= viewModel.getAllCustomers();}catch(Exception ex){MessageBox.Show(ex.InnerException.ToString());}}

And there we go with XML in the view

<DataGrid x:Name="DataGrid1"ItemsSource="{Binding NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>

It seems I've implemented everything, yet it doesnt work. If I add row or edit current row, there is no change in the database. Anyone knows how to fix it?



Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>