将IQueryable转换为BindingList

时间:2013-11-01 12:35:14

标签: c# winforms entity-framework bindingsource

从DataSource放置ObsevableCollection User作为新表单的详细信息,它创建所有textBoxes,BindingSource和BindingNavigator。这是优秀而快速的。

因为我只需要更新一个用户我删除了BindingNavigator。但是......

这可以不进行列表转换吗?

class UserDt : Forms {
    // Designer partial part
    this.userBindingSource.DataSource = typeof(WinFormswithEFSample.User);

    private void UserDt_Load
    {
        _context.Users.Load();

        // use this with BindNavigator to navigate ower all users
        //this.userBindingSource.DataSource = _context.Users.Local.ToBindingList();

        // this doesn't work
        //this.userBindingSource.DataSource = _context.Users.Where(p => p.Username == "admin").Local.ToBindingList();

        var query = _context.Users.Where(p => p.Username == "admin").ToList();
        var binding = new BindingList<User>(query);
        this.usersBindingSource.DataSource = binding;
    }
}

1 个答案:

答案 0 :(得分:4)

  

这可以不进行列表转换吗?

没有。
BindingListIList为参数 IQueryable无法投放到IList,因此您需要转换,就像您已经完成的那样:

    var query = _context.Users.Where(p => p.Username == "admin")
                              .ToList(); //converts the IQueryable to List
    var binding = new BindingList<User>(query);

如果你真的需要 BindingList并且无法满足于更简单的List