繁体   English   中英

使用实体框架的WPF MVVM?

[英]WPF MVVM with Entity Framework?

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

我有一个包含在项目中的Entity Framework .edmx,其中包含一个带有主要ID的'tbCountrys'表。

这是我的模型类,它仅声明一些与表中列相关的变量/属性并实现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
  }
}

我的视图模型还实现了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

      }
    }
  }

最后,我的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>

当我调试代码时,VIew模型中的try块未执行,并且catch异常被抛出。 我声明实体数据读取器对象后,我的while循环读取数据永远不会运行,因为它失败了。 也许我的查询语法有些不正确?

非常感谢您提供任何帮助,因为我在网上找不到很多将Entity Framework与MVVM结合使用的示例。 谢谢

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

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

您的连接字符串看起来确实错误。 代码在EntityConnection构造函数上失败

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

所以这是这行:

new EntityConnection("name=LDBEntities")

"name=LDBEntities"是哪种连接字符串?

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

new EntityConnection(SomeResource.LDBEntities)

暂无
暂无

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

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