[英]updating a database record with linq to sql in c#
我有一个看起来像这样的函数:
public UpdateRecord(MyObjectModel TheObject, int TheUserID)
{
using (MyDataContextModel TheDC = new MyDataContextModel())
{
var TheObjectInDB = (from o in TheDC.TheObjects
where o.ObjectID == TheObject.ObjectID
select new MyObjectModel()).SingleOrDefault();
if (TheObject.Prop1 != null) { TheObjectInDB.Prop1 = TheObject.Prop1; }
if (TheObject.Prop2 != null) { TheObjectInDB.Prop2 = TheObject.Prop2; }
TheDC.SubmitChanges();
}
}
代码没有崩溃,但是没有更新数据库。 我需要更改什么?
选择o代替new MyObjectMode(),修改:
var TheObjectInDB = (from o in TheDC.TheObjects
where o.ObjectID == TheObject.ObjectID
select o).SingleOrDefault();
首先,您确实在查询中select new MyObjectModel()
,它将始终根据您从数据库中提取的内容创建一个新的对象。 更改为select o
。
其次,在:
if (TheObject.Prop1 != null) { TheObjectInDB.Prop1 = TheObject.Prop1; }
if (TheObject.Prop2 != null) { TheObjectInDB.Prop2 = TheObject.Prop2; }
您可以有条件地更新对象的值。 因此,如果Prop1
和Prop2
为null,则不会更新对象的属性。
以下代码有效,并且几乎与您发布的代码相同。
DataContext dc = new DataContext(ConnectionString);
var q = from a in dc.GetTable<Employee>()
where a.EmployeeID == this.EmployeeID
select a;
Employee temp = q.Single<Employee>();
temp.EmployeeActiveStatus = this.EmployeeActiveStatus;
temp.EmployeeName = this.EmployeeName;
temp.EmployeeUserID = this.EmployeeUserID;
temp.EmployeeCreateModifyDate = this.EmployeeCreateModifyDate;
temp.EmployeePaperWork = this.EmployeePaperWork;
dc.SubmitChanges();
我看到的唯一主要区别是该行:选择新的MyObjectMode())。SingleOrDefault()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.