how to update a database using linq to sql

3k Views Asked by At

I am trying to change a value stored in a database but I am unsure on how to do that,

using (DataClassesDataContext dataContext = new DataClassesDataContext())
{        
int accounttype = 1;
int id = 123;
//Search database for record based on round and player nummber
var query = (from r in dataContext.Tables
            where r.accountType.Equals(accounttype)
            where r.ID.Equals(Id)
            select r);

//store player1s oppent in database
foreach (var record in query)
{
    record.fund = 1234;

    dataContext.Tables.InsertOnSubmit(record);
    dataContext.SubmitChanges();
}
}

so I'm trying to search the database for a particular record and change one of its values but I cannot seem to work out how to update it, I know that "InsertOnSubmit" is wrong though.

1

There are 1 best solutions below

5
On

Try this:

record.fund = 1234;
dataContext.Entry(record).State = EntityState.Modified;
dataContext.SaveChanges();

Also you may need to change your query like:

var query = (from r in dataContext.YourTable
             where r.accountType == accounttype &&  r.ID == Id 
             select r);