Linqtosql will not allow fields to be updated as they throw them as read-only

I have a problem updating linq on linqtosql

from below code

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 read-only. I haven't made this assignment anywhere and I can't see where the problem is.

+1


source to share


5 answers


When you select only individual fields, you create an anonymous type on the fly, which is no longer part of the ORM's change tracking / update mechanism.



You will need to change the selected part as "Select lqp" for it to work.

+2


source


You assign row.LastName on the first line of the For Each loop.

Will you copy with strict / explicit option on or off? If strict is specified on this line, it should not compile.



The reason you are seeing this is because creating an anonymous type for queries that contain an explicit Select clause, all properties of the resulting type will be read-only. It has the same effect as if all properties were declared anonymous using the Key field. For example

Dim x = New With { Key .Name ="foo" }

      

+1


source


When you created the dbml file for your data context, did it create the LastName property as a read field? Open the dbml, find the field and check the property to make sure it is set to read only ...

0


source


Both are considered to be set to false

Explicit and Option strict are also disabled

0


source


That single entity entity structure is better than Linq2Sql (really the only thing!). You can select different fields from different tables, and yet it can be updatable. With Linq2Sql, if you select from multiple tables (although you are not here, but when you create a new anonymous type, it's the same idea), it becomes read-only.

0


source







All Articles