views:

7653

answers:

5
+6  Q: 

Update using linq

how can i update a record against specific id in (Linq to sql)

A: 
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;

// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
Priyank Bolia
+7  A: 

LINQ is a query tool (Q = Query) - so there is no magic LINQ way to update just the single row, except through the (object-oriented) data-context (in the case of LINQ-to-SQL). To update data, you need to fetch it out, update the record, and submit the changes:

using(var ctx = new FooContext()) {
    var obj = ctx.Bars.Single(x=>x.Id == id);
    obj.SomeProp = 123;
    ctx.SubmitChanges();
}

Or write an SP that does the same in TSQL, and expose the SP through the data-context:

using(var ctx = new FooContext()) {
    ctx.UpdateBar(id, 123);
}
Marc Gravell
A: 

In the absence of more detailed info:

using(var dbContext=new dbDataContext())
{
    var data=dbContext.SomeTable.Where(row=>row.id==requiredId).FirstOrDefault();
    if(data!=null)
        data.SomeField=newValue;
    dbContext.SubmitChanges();
}
spender
That won't compile; Where(pred) will return an IQueryable<SomeType>, not a SomeType
Marc Gravell
oops. My bad. Corrected.
spender
You can use the Single(pred) instead of Where(pred).FirstOrDefault()...
Arjan Einbu
You live and learn. Cheers.
spender
+3  A: 
public bool UpdateCustomerIno(CustomerInfo toUpdate)
{
    bool successfullySaved = false;

    var db = new DataClasses1DataContext();
    try
    {
        var dbCstInfo = db.CustomerInfos
            .Where(w => w.CustomerID == toUpdate.CustomerID)
            .SingleOrDefault();

        if (dbCstInfo != null)
        {
            dbCstInfo.FirstName = toUpdate.FirstName;
            dbCstInfo.LastName = toUpdate.LastName;
            db.SubmitChanges();
            successfullySaved = true;
        }
    }
    catch {
        successfullySaved = false;
    }
    return successfullySaved;
}
Waheed
Not an issue here (since it is a new data-context), but there is a bug in DataContext that makes it more efficient to use (for identity lookups) SingleODefault(predicate) than Where(predicate).SingleOrDefault(). Also; if it fails, why wouldn't you let it throw an exception? Oh, and it is IDisposable.
Marc Gravell
A: 
Waheed
Why the hassle with the images, it's more useful and certainly better searchable to use the code layout feature
Sander Rijken
these are from scott gu's blog
sabbour
yes u are correct. these are from there..
Waheed