//来 self 的表格
BindingSource bs = new BindingSource();
private void fillStudentGrid()
{
bs.DataSource = Admin.GetStudents();
dgViewStudents.DataSource = bs;
}
//来自 Admin 类
public static List<Student> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
var query =
(from s in conn.Students
select new Student
{
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
}).ToList();
return query;
}
我试图在 Winforms 中填充一个 datagridview 控件,但我只需要其中的几个值。代码编译,但抛出运行时错误:
不允许在查询中显式构造实体类型“DojoManagement.Student”。
有没有办法让它以这种方式工作?
最佳答案
您已经有一个 IEnumerable<Student>
实例,并且由于描述的原因,您无法从查询中投影实体 here )
您也不需要创建一个列表来绑定(bind)到这个数据源 - 您可以通过将其更改为这样来大大简化您的方法:
public static IEnumerable<Student> GetStudents()
{
return new DojoDBDataContext().Students;
}
没有理由投影一个新实例来只映射一些属性,通过执行查询,您无论如何都会返回所有值,并且您的投影不会为您节省任何东西。如果出于信息隐藏的目的,您真的只想从此查询中返回几个值,您可以这样做:
public static IEnumerable<Object> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
return conn.Students
.Select(s => new {
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
});
}
编辑:如果您不使用 C# 4,则必须转换 IEnumerable<T>
的内容。至 Object
明确地。只有 C# 4 支持 IEnumerable<T>
的协方差.因此,如果您使用的是 C# 3,则必须这样做:
public static IEnumerable<Object> GetStudents()
{
DojoDBDataContext conn = new DojoDBDataContext();
return conn.Students
.Select(s => new {
ID = s.ID,
FirstName = s.FirstName,
LastName = s.LastName,
Belt = s.Belt
}).Cast<Object>();
}
关于c# - 从匿名 Linq 查询填充 WinForms DataGridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647172/