【问题标题】:MVVM in WPF with Entity Framework unhandled exceptionWPF 中的 MVVM 与实体框架未处理的异常
【发布时间】:2013-10-11 15:00:36
【问题描述】:

这快把我逼疯了。我对 WPF/EF 相当陌生。

我有一个简单的 MVVM 应用程序,它通过 XAML 中的绑定将实体表读入 DataGrid。该应用程序编译良好。

我得到了这个未处理的异常,但是它锁定了设计器:

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
at System.Data.Objects.ObjectContext.CreateEntityConnection(String connectionString)

XAML 无法创建我的视图模型的实例...

xmlns:vm="clr-namespace:Entity_MVVM"
    Title="MainWindow" Height="600" Width="800"
    DataContext="{DynamicResource MyViewModel}">
<Window.Resources>
    <vm:CountrysViewModel x:Key="MyViewModel"/>
</Window.Resources>

这是我的视图模型“加载网格”方法:

 public void LoadGrid()

    {
        var db = new LDBEntities();
        using (var conn = new EntityConnection("name=LDBEntities"))
        {
            conn.Open();
            EntityCommand cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT VALUE c FROM LDBEntities.tbCountrys as c";

            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(Exception e)
            {
                MessageBox.Show(string.Format("Can't read in data!"));
            }
        }

我的 App.config 中的连接字符串是在创建我的 EF 模型时创建的,并按预期填充 DataGrid。

任何想法是什么原因造成的?

周五下午的挫败感!谢谢

编辑:App.Config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="LDBEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source=DMEA-T1000\SQLEXPRESS;Initial Catalog=LDB;Persist Security Info=True;User ID=sa;Password=PasswordHidden;MultipleActiveResultSets=True' " providerName="System.Data.EntityClient" /></connectionStrings>
</configuration>

【问题讨论】:

  • 什么版本的 EF? 4?
  • IMO,使用这样的实体框架(就好像它是普通的旧 ADO.Net,带有所有这些魔术字符串和手动映射)完全违背了 ORM 的目的。
  • 发布您的 App.config。发生这种情况的一种方式是,如果您的数据模型无法连接到源。这显然发生在运行时,这就是它编译良好的原因。
  • 是的,我正在尝试了解由已离职开发人员编写的现有应用程序。我同意,我会使用 LINQ 而不是 EntityDataReader 等。
  • @hardgraf 代码全错了。删除它并正确重做它会节省您的时间和痛苦。

标签: c# wpf entity-framework xaml mvvm


【解决方案1】:

当您将 ERM 添加到项目中时,它会为您创建模型。

例如,如果您的数据库中有一个名为 tblYears 的表,您应该能够声明:

tblYear y = new tblYear();

我个人创建了一个本地模型并填充它以在视图中使用,即视图模型。

class YearModel : INotifyPropertyChanged
{

#region Members

    MyERM.tblYear _year;

#endregion

#region Properties

    public MyERM.tblYear Year
    {
        get { return _year; }
    }

    public Int32 id
    {
        get { return Year.id; }
        set
        {
            Year.id = value;
            NotifyPropertyChanged("id");
        }
    }

    public String Description
    {
        get { return Year.Description; }
        set
        {
            Year.Description = value;
            NotifyPropertyChanged("Description");
        }
    }

#endregion

#region Construction

    public YearModel()
    {
        this._year = new MyERM.Year
        {
            id = 0,
            Description = ""
        };
    }

#endregion
}

然后您可以使用此视图模型来填充列表 或作为单独的记录 - 列表示例:

class YearListModel
{
    myERM db = new myERM();

    #region Members

    private ObservableCollection<YearModel> _years;

    #endregion

    #region Properties

    public ObservableCollection<YearModel> Years
    {
        get { return _years; }
    }

    #endregion

    #region Construction

    public YearListModel()
    {
        _years = new ObservableCollection<YearModel>();

        foreach (MyERM.tblYear y in db.tblYears())
        {
            _years.Add(new YearModel
            {
                id = y.id,
                Description = y.Description
            }
          );
        }
    }

    #endregion
}

然后,例如,您可以将其发送到这样的页面:

xmlns:local="clr-namespace:MyProject.ViewModels"

<Page.Resources>
    <local:YearListModel x:Key="YearList" />
</Page.Resources>

并将其绑定到控件:

<ListView x:Name="listviewname"
          DataContext="{StaticResource ResourceKey=YearList}"
          ItemsSource="{Binding Path=Years}">
    <ListView.View>
        <GridView>
            <GridViewColumn x:Name="columnname" Header="Code" 
                            DisplayMemberBinding="{Binding Code}"/>
        </GridView>
    </ListView.View>
</ListView>

希望这对 GL 有所帮助

【讨论】:

  • 太好了,非常感谢您的帮助!只有 1 年的编程/c# 经验,这大大简化了事情。
  • 我似乎无法为 MyERM.TableName 创建一个对象(在我的例子中是 LDBEntities.tbCountrys)
  • 如果在添加 erm 实例后已将其添加到数据库中,则需要刷新 erm。如果刷新不起作用(错误),请复制名称,将其删除,然后使用相同的名称重新添加。然后数据库中的任何更新都将反映在 erm.xml 中。我必须这样做很多次,所以这是一种习惯。更改数据库 - 重新附加 edm(如果刷新不起作用)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-02
相关资源
最近更新 更多