带有实体框架的 WPF MVVM?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19291997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:49:34  来源:igfitidea点击:

WPF MVVM with Entity Framework?

c#wpfentity-frameworkxamlmvvm

提问by Hardgraf

I'm building a simple mvvm WPF app in VS2010 .NET4.0 with Entity Framework 4. I'm a WPF beginner with only 1 year's programming experience. Trying to bind a datagrid in my XAML to an Entity Framework model. I have an observable collection in my View Model but can't seem to read the data in?

我正在使用实体框架 4 在 VS2010 .NET4.0 中构建一个简单的 mvvm WPF 应用程序。我是一个只有 1 年编程经验的 WPF 初学者。尝试将 XAML 中的数据网格绑定到实体框架模型。我的视图模型中有一个可观察的集合,但似乎无法读取数据?

I have an Entity Framework .edmx included in the project which holds a single 'tbCountrys' table with a primary ID.

我在项目中包含一个实体框架 .edmx,它包含一个带有主 ID 的“tbCountrys”表。

Here's my model class which just declares some variables/properties related to columns in my table and implements INotifyPropertyChanged:

这是我的模型类,它只声明了一些与我的表中的列相关的变量/属性并实现了 INotifyPropertyChanged:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace Entity_MVVM
{
public class CountrysModel : INotifyPropertyChanged
{
    #region variables

    private string _CountryId;
    private string _ShortName;
    private string _LongName;

    # endregion

    # region Properties

    public string CountryId
    {
        get { return _CountryId; }
        set { _CountryId = value;
              OnPropertyChanged("CountryId");
        }
    }

    public string ShortName
    {
        get { return _ShortName; }
        set
        {
            _ShortName = value;
            OnPropertyChanged("ShortName");
        }
    }

    public string LongName
    {
        get { return _LongName; }
        set
        {
            _LongName = value;
            OnPropertyChanged("LongName");
        }
    }

    #endregion

    # region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    # endregion
  }
}

My View Model also implements INotifyPropertyChanged, declares an Observable Collection to store my query results and has a LoadGrid() method which should query my table with an EntityConnection and populate the Observable Collection. This doesn't seem to be working? I am invoking the LoadGrid() method from the constructor of my View Model:

我的视图模型还实现了 INotifyPropertyChanged,声明了一个 Observable 集合来存储我的查询结果,并且有一个 LoadGrid() 方法,该方法应该使用 EntityConnection 查询我的表并填充 Observable 集合。这似乎不起作用?我正在从我的视图模型的构造函数调用 LoadGrid() 方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.EntityClient;
using System.Data;
using System.Windows;
using System.Collections;


namespace Entity_MVVM
{
    public class CountrysViewModel : INotifyPropertyChanged
    {
    #region Constructor

    public CountrysViewModel()
    {
        LoadGrid();
    }

    # endregion

    # region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    # endregion

    # region ObservableCollection

    private ObservableCollection<CountrysModel> _CountrysModelObservableList = new ObservableCollection<CountrysModel>();
    public ObservableCollection<CountrysModel> CountrysModelObservableList
    {
        get { return _CountrysModelObservableList; }
        set
        {
            _CountrysModelObservableList = value;
            OnPropertyChanged("CountrysModelObservableList");
        }
    }

    # endregion

    # region Properties

    private CountrysModel _CountrysModelView;
    public CountrysModel CountrysModelView
    {
        get { return _CountrysModelView; }
        set
        {
            _CountrysModelView = value;
            OnPropertyChanged("CountrysModel");
        }
    }

    # endregion

    # region LoadGrid Method

    public void LoadGrid()
    {
        LDBEntities db = new LDBEntities();
        using (var conn = new EntityConnection("name=LDBEntities"))
        {
            conn.Open();
            EntityCommand cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT * FROM LDBEntities.tbCountrys";

            try
            {
                EntityDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection);

                _CountrysModelObservableList.Clear();

                while (rdr.Read())
                {
                    var cCountryId = rdr["CountryId"].ToString();
                    var cShortName = rdr["shortName"].ToString();
                    var cLongName = rdr["longName"].ToString();

                    _CountrysModelView = new CountrysModel()
                    {
                        CountryId = cCountryId,
                        ShortName = cShortName,
                        LongName = cLongName
                    };

                    _CountrysModelObservableList.Add(_CountrysModelView);
                }
            }
            catch
            {
                MessageBox.Show(string.Format("Can't read in data!"));
            }
        }

    #endregion

      }
    }
  }

Lastly, my XAML view:

最后,我的 XAML 视图:

<Window x:Class="Entity_MVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:Entity_MVVM"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{DynamicResource MyViewModel}">
    <Window.Resources>
        <vm:CountrysViewModel x:Key="MyViewModel"/>
    </Window.Resources>
    <Grid>
        <DataGrid Width="400" Height="127" Name="grdPublications" ItemsSource="{Binding Path=CountrysModelObservableList}">
        </DataGrid> 
    </Grid>
</Window>

When I debug the code, the try block in my VIew Model is not executed and the catch exception is thrown. My while loop to read in the data never runs as it bails out after I declare the EntityDataReader object. Maybe there is something not quite right with my query syntax?

当我调试代码时,我的 VIew 模型中的 try 块没有被执行,并抛出了 catch 异常。我读入数据的 while 循环永远不会运行,因为它在我声明 EntityDataReader 对象后退出。也许我的查询语法不太正确?

Any help would be most appreciated as I can't find many examples online of using the Entity Framework with MVVM. Thanks

任何帮助将不胜感激,因为我无法在网上找到许多将实体框架与 MVVM 结合使用的示例。谢谢

Also, getting this exception in the XAML, can't create an instance of my View Model. The connection string is correct in the App.config so not sure what's causing it...

此外,在 XAML 中获取此异常无法创建我的视图模型的实例。 App.config 中的连接字符串是正确的,所以不确定是什么原因造成的...

Also, getting this exception in the XAML, can't create an instance of my View Model. The connection string is correct in the App.config so not sure what's causing it...

此外,在 XAML 中获取此异常无法创建我的视图模型的实例。App.config 中的连接字符串是正确的,所以不确定是什么原因造成的...

回答by Cyril Gandon

You connection string looks really wrong. The code is failing on the EntityConnection constructor

你的连接字符串看起来真的错了。代码在 EntityConnection 构造函数上失败

at System.Data.EntityClient.EntityConnection.ctor(String connectionString)

So it is this line :

所以这是这一行:

new EntityConnection("name=LDBEntities")

What sort of connection string is that "name=LDBEntities"?

那是什么类型的连接字符串"name=LDBEntities"

I think you have forgotten to get the connection string from your ressource file.

我认为您忘记从您的资源文件中获取连接字符串。

new EntityConnection(SomeResource.LDBEntities)