0
votes

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. Trying to bind a datagrid in my XAML to an Entity Framework model. 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.

Here's my model class which just declares some variables/properties related to columns in my table and implements 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. This doesn't seem to be working? I am invoking the LoadGrid() method from the constructor of my View Model:

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:

<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. My while loop to read in the data never runs as it bails out after I declare the EntityDataReader object. 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. Thanks

Also, getting this exception in the XAML, can't create an instance of my View Model. The connection string is correct in the App.config so not sure what's causing it...

Also, getting this exception in the XAML, can't create an instance of my View Model. The connection string is correct in the App.config so not sure what's causing it...

1
Any reason why you are using entity framework - then hand cranking your sql and using data reader. Why not just query the entity context directly using LINQ?Richard Friend
Hi Richard. I am trying to figure out an application written by a departed dev who has used this method to read the data in. I have used LINQ before in a code-behind wpf app and agree it is much more straight forward.Hardgraf

1 Answers

2
votes

You connection string looks really wrong. The code is failing on the EntityConnection constructor

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

I think you have forgotten to get the connection string from your ressource file.

new EntityConnection(SomeResource.LDBEntities)