Ahmed Ali
Ahmed Ali

Reputation: 31

Entity Framework 7 and BindingList

I'm trying to use EF7 with Winforms and I want to use BindingList to support two-way binding

In EF6, I could do it by calling .ToBindingList

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

However in EF7, there is neither Local Property nor ToBindingList

How can I achieve two-way binding on Winforms with EF7?

Upvotes: 3

Views: 3352

Answers (1)

Ric .Net
Ric .Net

Reputation: 5550

You should never bind, especially not two-way directly to EF objects. This would mean you use a DbContext over the lifetime of the application, which will put you into trouble over time.

Using the EF objects doesn't make sense most of the time as you would almost never show the exact database object to the user. The view will in most cases show a composition of multiple data objects.

So instead of using the objects directly create tailor made viewmodels to show to the user, which you can fetch from a fresh DbContext. These viewmodels can implement INotifyPropertyChanged.

When done with the fetching dispose of the DbContext and create a new one when the user wants to save any changes.

So a quick sample:

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();
        }
    }
} 

The results can easily be wrapped in a BindingList

Upvotes: 2

Related Questions