none
LINQ2SQL Update RRS feed

  • Question

  • Hey guys;

    i'm new to LINQ and trying to update a field in the database. here is the code:

     

    Dim db As New ConstructionDBDataContext

     

    Dim changepwd = (From p In db.Users _

     

    Where p.UserID = Convert.ToString(Session("Userid")) _

     

    Select New With {p.Password}).Single

    changepwd.Password = NewPass.Text

    db.SubmitChanges()

    This code is doing nothing, even if i set the changepwd.Password = "to whatever"

    Can you help please?

    Thanks

    Sunday, May 3, 2009 8:57 PM

Answers

All replies

  • There is no change tracking for anonymous types. Change to "select p" instead.
    Kristofer - Huagati Systems Co., Ltd. - www.huagati.com - Cool tools for Linq-to-SQL and Entity Framework: www.huagati.com/dbmltools
    • Marked as answer by MikeJH73 Monday, May 4, 2009 6:16 PM
    Monday, May 4, 2009 1:12 AM
    Answerer
  • You need to select a whole row in order to update:

    Dim db as New ConstructionDBDataContext
    Dim userID = Convert.ToString(Session( "Userid" ))
    Dim user = db.Users.Single (Function(u) u.UserID = userID )     ' select whole User entity
    user.Password = NewPass.Text     ' now we can update
    db.SubmitChanges()

    Note that in this case, we don't actually need to query any data before doing the update. Therefore, we can make it more efficient by updating directly - by calling Attach:

    Dim db as New ConstructionDBDataContext
    Dim user = new User
    user.UserID = Convert.ToString(Session( "Userid" ))
    db.Users.Attach (user)
    user.Password = NewPass.Text
    db.SubmitChanges()

    Joe
    Write LINQ queries interactively - www.linqpad.net
    Monday, May 4, 2009 1:15 AM
    Answerer
  • Thanks a lot Kris, i appreciate your help.

    your solution worked out.

    thx again
    Monday, May 4, 2009 6:18 PM