简体   繁体   English

WPF中的MVVM和Entity Framework未处理的异常

[英]MVVM in WPF with Entity Framework unhandled exception

This is driving me mad. 这让我发疯。 I'm fairly new to WPF/EF. 我是WPF / EF的新手。

I have a simple MVVM app which reads an Entity Table into a DataGrid via binding in the XAML. 我有一个简单的MVVM应用程序,该应用程序通过XAML中的绑定将实体表读入DataGrid。 The app compiles fine. 该应用程序编译正常。

I am getting this unhandled exception however which locks the designer: 我遇到了这个未处理的异常,但是它锁定了设计器:

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)

The XAML cannot create an instance of my View Model... 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>

Here is my View Model 'Load Grid' method: 这是我的视图模型“加载网格”方法:

 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!"));
            }
        }

The connection string in my App.config was created on creation of my EF model and populates the DataGrid as intended. App.config中的连接字符串是在创建EF模型时创建的,并按预期填充了DataGrid。

Any ideas what is causing this? 任何想法是什么原因造成的?

Friday afternoon frustration! 星期五下午无奈! Thanks 谢谢

Edit: App.Config: 编辑: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>

When you add your ERM to the project it will create models for you. 将ERM添加到项目时,它将为您创建模型。

If you have a table in your db called tblYears for example you should be able to declare: 例如,如果数据库中有一个名为tblYears的表,则应该可以声明:

tblYear y = new tblYear();

I personally create a local model and populate it to use in the view ie viewmodel. 我个人创建了一个本地模型,并将其填充到视图中使用,即viewmodel。

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
}

You can then use this view model to either populate a List<> or as an individual record - list example: 然后,您可以使用此视图模型填充List <>或作为单个记录-列表示例:

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
}

Then for example you can send it to a page like so: 然后,例如,您可以将其发送到如下页面:

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

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

And bind it to a control: 并将其绑定到控件:

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

Hope this helps GL 希望这对GL有帮助

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

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