如何根据LINQ to SQL中的特定ID更新记录?
答案 0 :(得分:55)
LINQ是一个查询工具(Q = Query) - 所以除了通过(面向对象的)数据上下文(在LINQ-to-SQL的情况下)之外,没有神奇的LINQ方法来更新单行。要更新数据,您需要获取数据,更新记录并提交更改:
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);
}
答案 1 :(得分:19)
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;
}
答案 2 :(得分:8)
更新
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"
答案 3 :(得分:5)
缺乏更详细的信息:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
答案 4 :(得分:2)
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
答案 5 :(得分:2)
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();
答案 6 :(得分:0)
我在一周前找到了解决方法。您可以使用带有“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
语句中,您可以直接发送查询,并使用您要更新的特定记录的值。
value = 0 - > 0是记录的新值;
code = {0} - >是您将发送过滤器值的字段;
代码 - >是该领域的新价值;
我希望这个参考有所帮助。