How to update the database with new information

I am terrible with databases, so please carry me.

I have a program that gets some user information and adds it to the database table. Then I will need to get additional information for this table and update it. For this, I tried to do this:

    public static void updateInfo(string ID, string email, bool pub)
    {
        try
        {
            //Get new data context
            MyDataDataContext db = GetNewDataContext(); //Creates a new data context

            //Table used to get user information
            User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));

            //Checks to see if we have a match
            if (user != null)
            {
                //Add values
                user.Email = email;
                user.Publish = publish;
            }

            //Prep to submit changes
            db.Users.InsertOnSubmit(user);
            //Submit changes
            db.SubmitChanges();
        }
        catch (Exception ex)
        {
            //Log error
            Log(ex.ToString());
        }
    }

But I get this error:

  System.InvalidOperationException: Unable to add an entity that already exists.

I know this because I already have an entry in the table, but I don’t know how to edit the code for the update, and not try to create a new one?

Why is this not working? Wouldn’t send changes to the current update item of this item and create a new one?

+5
1

//Prep to submit changes
db.Users.InsertOnSubmit(user);

, .

, .

/. :

public static void updateInfo(string ID, string email, bool pub)
{
    try
    {
        using (MyDataDataContext db = GetNewDataContext()) 
        {
            User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));

            if (user != null)
            {
                user.Email = email;
                user.Publish = publish;
            }

            db.SubmitChanges();
        }
    }
    catch (Exception ex)
    {
        //Log error
        Log(ex.ToString());

        // TODO: Consider adding throw or telling the user of the error.
        // throw;

    }
}
+7

All Articles