leonyx
leonyx

Reputation: 857

Linq update record

How do you update a record with a specific ID in LINQ to SQL (ASP.Net / C#)?

Upvotes: 6

Views: 12393

Answers (3)

BJ Patel
BJ Patel

Reputation: 6268

Look at this piece of code for example.

void UpdateRow(Int32 intID)
{
    bool IsSuccessfullyUpdated = false;

    var db = new DataContext();
    try
    {
        var dbCstInfo = db.TableName
            .Where(w => w.ID == intID)
            .SingleOrDefault();

        if (dbCstInfo != null)
        {
            dbCstInfo.IsActive = !dbCstInfo.IsActive;
            dbCstInfo.Name = "BJP";
            dbCstInfo.Comp = "PVtal";
            db.SubmitChanges();
            IsSuccessfullyUpdated = true;
        }
    }
    catch
    {
        IsSuccessfullyUpdated = false;
    }

    return IsSuccessfullyUpdated;

}

Upvotes: 0

user110714
user110714

Reputation:

You can do it like this...

var record = 
(
   from x in db.TableName
   where x.Id == 12345
   select x
)
.Single();

record.DateUpdated = DateTime.Now;

db.SubmitChanges();

Hope it helps :)

Upvotes: 16

Eoin Campbell
Eoin Campbell

Reputation: 44268

Care to post some sample code you've taken a stab at.

If it's linq2sql, then it should be a simple matter of Retrieving your object using your linq datacontext using a Where<T>() clause , updating the object property and then calling the DataContext.SubmitChanges()

Upvotes: 0

Related Questions