简体   繁体   English

使用实体框架的WPF MVVM?

[英]WPF MVVM with Entity Framework?

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. 我正在使用Entity Framework 4在VS2010 .NET4.0中构建一个简单的mvvm WPF应用程序。我是一位只有1年编程经验的WPF初学者。 Trying to bind a datagrid in my XAML to an Entity Framework model. 尝试将XAML中的数据网格绑定到实体框架模型。 I have an observable collection in my View Model but can't seem to read the data in? 我的视图模型中有一个可观察的集合,但似乎无法读取其中的数据?

I have an Entity Framework .edmx included in the project which holds a single 'tbCountrys' table with a primary ID. 我有一个包含在项目中的Entity Framework .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. 我的视图模型还实现了INotifyPropertyChanged,声明了一个Observable集合来存储我的查询结果,并具有一个LoadGrid()方法,该方法应使用EntityConnection查询我的表并填充Observable集合。 This doesn't seem to be working? 这似乎不起作用吗? I am invoking the LoadGrid() method from the constructor of my View Model: 我从我的视图模型的构造函数调用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. 当我调试代码时,VIew模型中的try块未执行,并且catch异常被抛出。 My while loop to read in the data never runs as it bails out after I declare the EntityDataReader object. 我声明实体数据读取器对象后,我的while循环读取数据永远不会运行,因为它失败了。 Maybe there is something not quite right with my query syntax? 也许我的查询语法有些不正确?

Any help would be most appreciated as I can't find many examples online of using the Entity Framework with MVVM. 非常感谢您提供任何帮助,因为我在网上找不到很多将Entity Framework与MVVM结合使用的示例。 Thanks 谢谢

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

Also, getting this exception in the XAML, can't create an instance of my View Model. 另外,在XAML中获取此异常无法创建我的视图模型的实例。 The connection string is correct in the App.config so not sure what's causing it... App.config中的连接字符串正确,因此不确定是什么原因...

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)

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

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