Pra*_*ana 22 c# linq asp.net datacontext linq-to-sql
我可以更新下面函数中给出的员工记录,还是先查询员工集合,然后更新数据?
public int updateEmployee(App3_EMPLOYEE employee)
{
DBContextDataContext db = new DBContextDataContext();
db.App3_EMPLOYEEs.Attach(employee);
db.SubmitChanges();
return employee.PKEY;
}
Run Code Online (Sandbox Code Playgroud)
或者我必须做以下事情?
public int updateEmployee(App3_EMPLOYEE employee)
{
DBContextDataContext db = new DBContextDataContext();
App3_EMPLOYEE emp = db.App3_EMPLOYEEs.Single(e => e.PKEY == employee.PKEY);
db.App3_EMPLOYEEs.Attach(employee,emp);
db.SubmitChanges();
return employee.PKEY;
}
Run Code Online (Sandbox Code Playgroud)
但我不想使用第二种选择.有没有有效的方法来更新数据?
我通过两种方式得到此错误:
已尝试附加或添加非新的实体,可能已从另一个DataContext加载.这不受支持.
我找到了以下解决此问题的方法:
1)获取和更新实体(我将使用这种方式,因为它对我来说没问题)
public int updateEmployee(App3_EMPLOYEE employee)
{
AppEmployeeDataContext db = new AppEmployeeDataContext();
App3_EMPLOYEE emp = db.App3_EMPLOYEEs.Single(e => e.PKEY == employee.PKEY);
emp.FIRSTNAME = employee.FIRSTNAME;//copy property one by one
db.SubmitChanges();
return employee.PKEY;
}
Run Code Online (Sandbox Code Playgroud)
2)禁用ObjectTrackingEnabled如下
// but in this case lazy loading is not supported
public AppEmployeeDataContext() :
base(global::LinqLibrary.Properties.Settings.Default.AppConnect3DBConnectionString, mappingSource)
{
this.ObjectTrackingEnabled = false;
OnCreated();
}
Run Code Online (Sandbox Code Playgroud)
3)分离所有相关对象
partial class App3_EMPLOYEE
{
public void Detach()
{
this._APP3_EMPLOYEE_EXTs = default(EntityRef<APP3_EMPLOYEE_EXT>);
}
}
public int updateEmployee(App3_EMPLOYEE employee)
{
AppEmployeeDataContext db = new AppEmployeeDataContext();
employee.Detach();
db.App3_EMPLOYEEs.Attach(employee,true);
db.SubmitChanges();
return employee.PKEY;
}
Run Code Online (Sandbox Code Playgroud)
4)在列中使用时间戳
http://www.west-wind.com/weblog/posts/135659.aspx
Run Code Online (Sandbox Code Playgroud)
5)创建用于更新数据的存储过程,并通过db context调用它