如何将从EF返回的列表转换为wpf中的observableList

时间:2016-07-20 12:50:51

标签: wpf entity-framework

我是wpf的新手。我正在尝试使用entityframework在wpf中创建crud。 这是我的模特

 class User : INotifyPropertyChanged
{
    private string _id;
    private string _firstName;
    private string _lastName;


    public User()
    {
    }

    public string ID
    {
        get { return _id; }
        set
        {
            _id = value;
            NotifyOfPropertyChange("ID");
        }
    }
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            NotifyOfPropertyChange("FirstName");
        }
    }
    public string LastName
    {
        get { return _lastName; }
        set
        {
            _lastName = value;
            NotifyOfPropertyChange("LastName");
        }
    }


    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyOfPropertyChange(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

当我添加ado.net数据模型文件时,它会像这样创建类

 public partial class User
{
    public string ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

所以当我尝试分配列表时这样

 ObservableCollection<User> lst = new ObservableCollection<User>();
            lst = _entity.Users.ToList();

它给了我错误

Error   1   Cannot implicitly convert type 'System.Collections.ObjectModel.ObservableCollection<TEST.User>' to 'System.Collections.Generic.List<TEST.Model.User>'   D:\my_backup\WPF\TEST\TEST\Model\PersonnelBusinessObject.cs 15  24  TEST

如何根据我的class formate.please帮助将其转换为。

1 个答案:

答案 0 :(得分:3)

您可以通过LINQ Select方法将一种集合类型映射到另一种:

using System.Linq;
...

var lst = new ObservableCollection<User>(
    _entity.Users.Select(u =>
        new User { ID = u.ID, FirstName = u.FirstName, LastName = u.LastName }));