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
2009-05-26 10:23:34
+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
2009-05-26 10:25:07
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
2009-05-26 10:25:24
That won't compile; Where(pred) will return an IQueryable<SomeType>, not a SomeType
Marc Gravell
2009-05-26 10:26:39
oops. My bad. Corrected.
spender
2009-05-26 10:33:10
You can use the Single(pred) instead of Where(pred).FirstOrDefault()...
Arjan Einbu
2009-05-26 10:35:53
You live and learn. Cheers.
spender
2009-05-26 10:40:44
+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
2009-05-26 10:28:01
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
2009-05-26 10:30:43
A:
Waheed
2009-05-26 10:32:33
Why the hassle with the images, it's more useful and certainly better searchable to use the code layout feature
Sander Rijken
2009-05-26 10:55:00