0

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? Commented Oct 7, 2013 at 12:01
  • 1
    And you should be putting your context in a using block. Commented Oct 7, 2013 at 12:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou, I now call my .GetData method from the ViewModel constructor.
1

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();
}

1 Comment

Yes, thankyou. Stupid mistake, still a beginner but learning every day!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.