簡體   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