views:

179

answers:

1

I just started playing with Linq to entities in a windows forms application and am not understanding one behavior that looks so simple though.

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 

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

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.

+1  A: 

There is an MSDN article about this.

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.

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.

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.

Edit: 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."

Jesse Millikan