c# - Entity Framework 7 和 BindingList

标签 c# winforms entity-framework bindinglist

我正在尝试将 EF7 与 Winforms 结合使用,并且我想使用 BindingList 来支持双向绑定(bind)

在 EF6 中,我可以通过调用 .ToBindingList 来完成此操作

_context = new ProductContext();
_context.Categories.Load(); 
this.categoryBindingSource.DataSource =
_context.Categories.Local.ToBindingList();

但是在 EF7 中,既没有 Local 属性也没有 ToBindingList

如何使用 EF7 在 Winforms 上实现双向绑定(bind)?

最佳答案

您永远不应该绑定(bind)到 EF 对象,尤其是不要双向直接绑定(bind)到 EF 对象。这意味着您在应用程序的整个生命周期内都使用 DbContext,这会随着时间的推移给您带来麻烦。

大多数时候使用 EF 对象没有意义,因为您几乎永远不会向用户显示确切的数据库对象。在大多数情况下, View 将显示多个数据对象的组合。

因此,与其直接使用对象,不如创建定制的 View 模型来显示给用户,您可以从新的 DbContext 中获取它。这些 View 模型可以实现 INotifyPropertyChanged

完成提取后,处理 DbContext 并在用户想要保存任何更改时创建一个新的。

快速示例:

public class UserViewModel : INotifyPropertyChanged
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int GroupId { get; set; }
    public string GroupName { get; set; }

    // INotifyPropertyChanged implementation or use Fody
}

public class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual GroupModel Group { get; set; }
}

public class GroupModel
{
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual HashSet<UserModel> Users { get; set; } 
}

public class UserRepository
{
    public IEnumerable<UserViewModel> GetUsers()
    {
        using (var db = new YourDbContext())
        {
            return (
                from user in db.Users
                select new UserViewModel
                {
                    UserId = user.Id,
                    UserName = user.Name,
                    GroupId = user.Group.Id,
                    GroupName = user.Group.Name,
                }).ToArray();
        }
    }
    public void SaveChanges(UserViewModel user)
    {
        using (var db = new YourDbContext())
        {
            // get user
            // modify and...
            db.SaveChanges();
        }
    }
} 

结果可以很容易地包装在 BindingList

关于c# - Entity Framework 7 和 BindingList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35903428/

相关文章:

c# - C#中如何处理切换用户?

c# - 在新线程中运行函数 C# Windows 应用程序

c# - mvc 数据库的第一个问题是 edmx/relationships 和显示 id 字段的 View

c# - 数据集 - 类模型 - 如何从数据集中获取 bool 值

c# - 我什么时候应该使用中性文化?它有什么必要?为什么不强制使用特定文化?

c# - ProgressBar 将我的代码减慢了 ~25 倍 [Async]

asp.net-mvc - 单独项目中的 VS2010 MVC 和 Entity Framework 模型

javascript - 在 index.d.ts 构建错误中找不到名称 'Record'

c# - 如何捕获EXE文件C#返回的响应

c# - LINQ to Entities 不支持扩展方法?