views:

121

answers:

6

I am having an issue with linq updating in linqtosql

from the code below

Dim lqPatientTable As New lqHospitalDataContext
    Dim strPatientId As String
    strPatientId = Me.ucboPatientInfo.SelectedRow.Cells(5).Value

    Dim lqPatientName = (From lqp In lqPatientTable.Patients _
                             Where lqp.PatientID = strPatientId _
                             Select lqp.FirstName, lqp.LastName)
    For Each row In lqPatientName
        row.LastName = utxtPatientLastName.Text
        row.FirstName = utxtPatientFirstName.Text
    Next
    lqPatientTable.SubmitChanges()

Visual Studio tells me that row.LastName is readonly I have not made that asignment anywhere, and I cannot see where the issue is.

+1  A: 

You assign to row.LastName in the first line of the "For Each" loop.

Are you copmiling with option strict/explicit on or off? If option strict is on that line should not compile.

The reason you are seeing this is when creating an anonymous type for queries which contain an explicit Select clause, all properties on the resulting type will be readonly. It has the same effect as if all of the properties were declared on an anonymous type using the Key field. For Example

Dim x = New With { Key .Name ="foo" }
JaredPar
So in order to have write access to the fields, you would have to select the whole object? Select lqpThat's good to know...
BenAlabaster
In VB the select clause is un-necessary. If it is ommitted VB will select the result of the last LINQ clause. In this case lqp
JaredPar
Interesting... you learn something new every day
BenAlabaster
A: 

When you created the dbml file for your data context, did it create the LastName property as a readonly field? Open the dbml find the field and check the property to see if it's set to readonly...

BenAlabaster
A: 

Readonly on both is set to false

Option Explicit and Option strict are also both off

Sean
Where are you getting the ReadOnly property from?
JaredPar
A: 

That's the one thing entity framework has better than Linq2Sql (really the only thing!). You can select various fields from different tables, and yet it can still be updateable. With Linq2Sql, if you select from multiple tables (even though here you aren't but when you create a new anonymous type, it's the same idea) it becomes read-only.

BFree
+2  A: 

When you select just individual fields you are creating an anonymous type on the fly that is no longer part of the ORM's change tracking/update mechanism.

You will need to change the select part to be "Select lqp" for this to work.

DamienG
A: 

Thanks DamienG that fixed the issue, back to the books.

Sean