问题描述
//从我的表单
BindingSource bs = new BindingSource();
private void fillStudentGrid()
{
bs.DataSource = Admin.GetStudents();
dgViewStudents.DataSource = bs;
}
//从管理类
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控件,我只想一些价值观。代码编译,但会抛出运行时错误:
I'm trying to fill a datagridview control in Winforms, and I only want a few of the values. The code compiles, but throws a runtime error:
不允许在查询中显式实现实体类型DojoManagement.Student的构造。
有没有办法让它以这种方式工作?
Is there a way to get it working in this manner?
推荐答案
您已经有一个 IEnumerable< Student>
实例,因为)
You already have an IEnumerable<Student>
instance and you cannot project entities from a query for the reasons described here)
你也不需要创建一个绑定到此数据源的列表 - 您可以通过将其更改为以下方式来大大简化您的方法:
You also don't need to create a list to bind to this data source - you can greatly simplify your method by changing it to this:
public static IEnumerable<Student> GetStudents()
{
return new DojoDBDataContext().Students;
}
没有理由投射一个新的实例来只映射几个属性,通过执行查询,您返回所有的值无论如何,您的投影不会保存任何东西。如果你真的只想从这个查询返回一些值,以便隐藏信息,你可以这么做:
There is no reason to project a new instance to only map a few of the properties, by executing the query you are returning all the values anyhow and your projection doesn't save you anything. If you really want to only return a few values from this query for the purposes of information hiding you could do this:
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,你必须这样做:
If you aren't using C# 4 you will have to cast the contents of the IEnumerable<T>
to Object
explicitly. Only C# 4 supports covariance for IEnumerable<T>
. So if you are using C# 3 you will have to do this:
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>();
}
这篇关于从匿名Linq查询填充WinForms DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!