我正在尝试将 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/