如何在LINQ to SQL中根据特定的ID更新记录?
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 存储过程实现相同的功能,并通过数据上下文公开该存储过程:
using(var ctx = new FooContext()) {
ctx.UpdateBar(id, 123);
}
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();
我在一周前找到了一个解决方法。您可以使用"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} --> 是您将发送过滤器值的字段;
Code --> 是字段的新值;