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


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

    Can you help please?


    Sunday, May 3, 2009 8:57 PM


All replies

  • There is no change tracking for anonymous types. Change to "select p" instead.
    Kristofer - Huagati Systems Co., Ltd. - - Cool tools for Linq-to-SQL and Entity Framework:
    • Marked as answer by MikeJH73 Monday, May 4, 2009 6:16 PM
    Monday, May 4, 2009 1:12 AM
  • 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

    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

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

    your solution worked out.

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