将Linq To Entities查询结果绑定到datagridview [英] Binding Linq To Entities query results to a datagridview
问题描述
我刚刚开始使用Linq来处理Windows窗体应用程序中的实体,但是我不了解一种看起来如此简单的行为.
I just started playing with Linq to entities in a windows forms application and am not understanding one behavior that looks so simple though.
如果我在下面键入代码,则我的dataGridView中将获得ReadOnly记录
If i type code below, i get ReadOnly records in my dataGridView
Dim x = From n in Table1 _
Select n.FirstName, n.LastName, N.Department
DataGridView1.DataSource = x
但是,如果我输入以下代码,我的dataGridView中将获得可编辑的行
But if i type the following code, i get editable rows in my dataGridView
Dim x = From n in Table1 _
Select n
DataGridView1.DataSource = x
因此,基本上,如果我指定要选择的列名称并将其数据绑定到我的DataGridView1,则行是只读的,但是如果我未指定列名称并将数据绑定到DataGridView,则这些行是可编辑的,并且我不明白为什么
So, basically if i specify the column names to select and databind to my DataGridView1, the rows are readonly but if i do not specify the column names and databind to the DataGridView, the rows are editable and i don't understand why.
推荐答案
After a little searching and lots of editing my answer, it seems like the culprit must be anonymous types. The documentation indicates that the non-key fields of anonymous types should be read-write, but you might be invoking some kind of exception to this rule. I would debug in and check the exact type of x in both cases.
此博客条目由某人提供. 在要生成密钥的任何情况下,LINQ查询表达式都会自动使用密钥字段(例如,分组依据,[...]").可能是使用Select
方法创建的字段会自动关键属性.
There's another possible hint in this blog entry by someone. "The LINQ query expressions will automatically use Key fields in any situation where a key is going to be generated (for example, Group By), [...]" It might be that fields created by using the Select
method are automatically Key properties.
另一个 Stackoverflow答案提示这-通过将Key
放在其他类型的字段上,它们与Select方法调用的某些结果的类型匹配.
Another Stackoverflow answer hints at this - they match the type of some results from a Select method call by putting Key
on the fields of the other type.
并且此文章(感谢Greg Stuntz)说出来. Geez.编写LINQ查询时,可以通过省略New With和{}来简化匿名类型定义,但是请注意,这会创建完全不可变的类型."
And this article (thanks, Greg Stuntz) comes right out and says it. Geez. "You can simplify the anonymous type definition when writing a LINQ query by omitting the New With and the { }'s, but be aware this creates fully immutable types."
这篇关于将Linq To Entities查询结果绑定到datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!