使用LINQ to SQL进行更新

我怎样才能更新logging对特定的ID在LINQ to SQL?

LINQ是一个查询工具(Q = Query) – 所以除了通过(面向对象的)数据上下文(在LINQ到SQL的情况下),没有什么奇妙的LINQ方法来更新单个行。 要更新数据,您需要将其取出,更新logging并提交更改:

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

或者编写一个在TSQL中执行相同的SP,并通过数据上下文暴露SP:

 using(var ctx = new FooContext()) { ctx.UpdateBar(id, 123); } 
 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; } 

更新

 NorthwindDataContext db = new NorthwindDataContext(); Product product = db.Products.Single(p => p.ProductName == "Toy 1"); product.UnitPrice = 99; product.UnitsInStock = 5; db.SubmitChanges(); 

 Dim db As New NorthwindDataContext ' Create New category and Products Dim category As New Category category.CategoryName = "Scott's Toys" Dim product1 As New Product category.ProductName = "Toy 1" Dim product2 As New Product category.ProductName = "Toy 2" 

在没有更详细的信息的情况下:

 using(var dbContext = new dbDataContext()) { var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId); if(data != null) { data.SomeField = newValue; } dbContext.SubmitChanges(); } 
 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 
  DataClassesDataContext dc = new DataClassesDataContext(); FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1); fd.FatherName=txtFatherName.Text; fd.FatherMobile=txtMobile.Text; fd.FatherOccupation=txtFatherOccu.Text; fd.MotherName=txtMotherName.Text; fd.MotherOccupation=txtMotherOccu.Text; fd.Phone=txtPhoneNo.Text; fd.Address=txtAddress.Text; fd.GuardianName=txtGardianName.Text; dc.SubmitChanges(); 

我在一周前find了一个解决方法。 您可以使用直接命令与“ ExecuteCommand ”:

 MDataContext dc = new MDataContext(); var flag = (from f in dc.Flags where f.Code == Code select f).First(); _refresh = Convert.ToBoolean(flagRefresh.Value); if (_refresh) { dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code); } 

ExecuteCommand语句中,您可以直接发送查询,并使用要更新的特定logging的值。

值= 0 – > 0是logging的新值;

代码= {0} – >是您将发送filter值的字段;

代码 – >是该字段的新值;

我希望这个参考有帮助。