开发者

How to use Linq to SQL to update certain fields only of entity?

开发者 https://www.devze.com 2023-03-01 09:41 出处:网络
How to use Linq to SQL to update certain fields only of entity? ASPX Page: Dim pdf As New Dashboard.Process_PDF()

How to use Linq to SQL to update certain fields only of entity?

ASPX Page:

    Dim pdf As New Dashboard.Process_PDF()
    pdf.ID = ID
    pdf.Label = rtbLabel.Text
    pdf.IsShared = cbxIsShared.Checked
    pdf.AccountID = AccountID

    If RadUpload1.UploadedFiles.Count > 0 Then  '<-- Uploading a new file is optional in Update Form but is required for Insert (Insert works fine)'
        Dim imageFile As UploadedFile = Nothing
        imageFile = RadUpload1.UploadedFiles(0)
        Dim bytes() As Byte = New Byte(imageFile.InputStream.Length - 1) {}
        imageFile.InputStream.Read(bytes, 0, CInt(imageFile.InputStream.Length))
        pdf.FileName = imageFile.FileName
        pdf.FileBytes = bytes
        pdf.FileSize = imageFile.ContentLength
        pdf.ContentType = imageFile.ContentType
        pdf.UploadedBy = RUserName
    End If

    pdf.Update()

Process_PDF.vb - version1

If I have this (below) then nothing happens. No error. No update.

Public Sub Update(开发者_JAVA技巧)
    dc.Process_PDFs.Attach(Me)
    dc.SubmitChanges()
End Sub

Process_PDF.vb - version2

If I have this (below) then I get an error on the Attach line:

An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.

Public Sub Update()
    dc.Process_PDFs.Attach(Me,True) '<--- ERRORS OUT HERE'
    dc.SubmitChanges()
End Sub

Process_PDF.vb - version3

If I have this (below) then it works perfectly IF I update the file also but if I don't update the file I get an error on the SubmitChanges line (no matter what the Update Check settings are set to):

Cannot insert the value NULL into column 'FileName', table 'MyDbName.dbo.Process_PDFs'; column does not allow nulls. UPDATE fails. The statement has been terminated.

Public Sub Update()
    dc.Process_PDFs.Attach(Me)
    dc.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, Me)
    dc.SubmitChanges() '<--- ERRORS OUT HERE IF NO FILE UPDATE'
End Sub


Well, the cleanest way is to retrieve the entity, update the fields that need to be updated, and call SubmitChanges(). (Creating a new entity, and copying the attributes has the disadvantage that if new fields are added to the entity than you need to update the code, so it's not easy to maintain)+ Anyways LINQ needs to original entity so that it can determine the fields that were updated...

0

精彩评论

暂无评论...
验证码 换一张
取 消