0
votes

I'm a beginner with WPF & MVVM.

I have a view with a datagrid. I've set the datacontext to my View Model & set the binding to my IBindingList. My Model consists of an ADO.NET edmx.

I'm querying my EF table from the ViewModel using Linq. It seems that the query has to be in a method to avoid the Error 'A field initializer cannot reference the non-static field, method, or property 'Entity_MVVM.ViewModels. etc.'

So here is my code which queries my EF table into a IBindingList. How do I then invoke my GetData method to expose the query results in my view?

namespace Entity_MVVM.ViewModels

 public class ContractViewModel : INotifyPropertyChanged
  {

   public void GetData()
   {
       LDBEntities db = new LDBEntities();

       IBindingList contracts = ((from c in db.tbContracts
                                  select new { c.Contract_ID, c.Contract_name, c.Country }
     ) as IListSource).GetList() as IBindingList;

   }

   public event PropertyChangedEventHandler PropertyChanged;
 }
}

Thanks all

2
When do you want to use your method?Sasha
And you should be putting your context in a using block.Sasha

2 Answers

2
votes

Instance Vairable cannot be used to initialize another varible ,since compiler may not execute in same order.

Try moving LDBEntities db = new LDBEntities() to view model constructor.

1
votes

Like Sasha is asking: it depends on when you want the data to be show. If you want it when the view is showing, just put it in the constructor:

public ContractViewModel 
{
   GetData();
}