简体   繁体   English

WPF MVVM中的ADO.NET实体框架?

[英]ADO.NET Entity Framework in WPF MVVM?

I'm a beginner with WPF & MVVM. 我是WPF和MVVM的初学者。

I have a view with a datagrid. 我有一个数据网格的看法。 I've set the datacontext to my View Model & set the binding to my IBindingList. 我已经将datacontext设置为我的视图模型,并将绑定设置为我的IBindingList。 My Model consists of an ADO.NET edmx. 我的模型包含一个ADO.NET edmx。

I'm querying my EF table from the ViewModel using Linq. 我正在使用Linq从ViewModel查询我的EF表。 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. 看来查询必须在一种方法中,以避免出现错误'字段初始化器无法引用非静态字段,方法或属性'Entity_MVVM.ViewModels。 etc.' 等等。'

So here is my code which queries my EF table into a IBindingList. 这是将我的EF表查询到IBindingList中的代码。 How do I then invoke my GetData method to expose the query results in my view? 然后,如何调用我的GetData方法以在视图中公开查询结果?

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 谢谢大家

Instance Vairable cannot be used to initialize another varible ,since compiler may not execute in same order. 实例Vairable不能用于初始化另一个变量,因为编译器的执行顺序可能不同。

Try moving LDBEntities db = new LDBEntities() to view model constructor. 尝试移动LDBEntities db = new LDBEntities()以查看模型构造函数。

Like Sasha is asking: it depends on when you want the data to be show. 就像Sasha在问的那样:这取决于您希望何时显示数据。 If you want it when the view is showing, just put it in the constructor: 如果在显示视图时需要它,只需将其放在构造函数中:

public ContractViewModel 
{
   GetData();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM