将 IQueryable 转换为 BindingList

Vla*_*nac 3 c# entity-framework bindingsource winforms

ObsevableCollection User数据源作为详细信息放置在新表单上,它会创建所有文本框、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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jen*_*ter 5

这可以不转换列表吗?

不。
TheBindingList将 anIList作为参数。
IQueryable不能转换为 an IList,因此您需要像已经完成的那样转换它:

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

如果你确实需要BindingList,不能满足于简单的List