我正在使用Linq2Sql并尝试更新表。
但是当我尝试更新列时没有更新。
我已尝试使用attach语句,但后来出现重复键错误。
我正在使用我自己的实体并将其复制到上下文实体,如您所见。
这是我的问题吗?
这是我的保存方法。
public void SaveUser(User user)
{
Mylester.Domain.DataContext.User sqluser = new Mylester.Domain.DataContext.User();
sqluser.usrID = user.ID;
sqluser.usrEmployeeID = user.EmployeeID;
sqluser.usrFirstName = user.FirstName;
sqluser.usrLastName = user.LastName;
sqluser.usrPassword = user.Password;
sqluser.usrEmail = user.Email;
sqluser.usrModified = user.Modified;
sqluser.usrCreated = user.Created;
sqluser.usrLastLoggedOn = user.LastLoggedOn;
sqluser.usrBrowserUsed = user.BrowserUsed;
sqluser.usrLoginOnly = user.LoginOnly;
sqluser.usrViewedWeeklyTimesheetChanges = user.ViewedWeeklyTimesheetChanges;
sqluser.usrActive = user.Active;
//_dbctx.Users.Attach(sqluser);
_dbctx.SubmitChanges();
}
这是我的测试方法。
[TestMethod]
public void UpdateUser()
{
User user;
user = _service.GetUser(1474);
user.FirstName = "TestXXXX";
_service.SaveUser(user);
user = _service.GetUser(1474);
Assert.AreEqual(user.FirstName, "TestXXXX");
}
答案 0 :(得分:0)
我正在使用我自己的实体并将其复制到上下文实体,如您所见。
这是我的问题吗?
是的,这会破坏DataContext
s identity map(用于实体跟踪)。最简单的更新方式是:
User user = _dbctx.Users.Single(u => u.usrID == 1474);
user.FirstName = "TestXXXX";
_dbctx.SubmitChanges();
答案 1 :(得分:-1)
在提交更改之前,您应该添加语句"dbcontext.tablename.InserOnSubmit(object);"
方法
public void SaveUser(User user)
{
Mylester.Domain.DataContext.User sqluser = new Mylester.Domain.DataContext.User();
sqluser.usrID = user.ID;
sqluser.usrEmployeeID = user.EmployeeID;
sqluser.usrFirstName = user.FirstName;
sqluser.usrLastName = user.LastName;
sqluser.usrPassword = user.Password;
sqluser.usrEmail = user.Email;
sqluser.usrModified = user.Modified;
sqluser.usrCreated = user.Created;
sqluser.usrLastLoggedOn = user.LastLoggedOn;
sqluser.usrBrowserUsed = user.BrowserUsed;
sqluser.usrLoginOnly = user.LoginOnly;
sqluser.usrViewedWeeklyTimesheetChanges = user.ViewedWeeklyTimesheetChanges;
sqluser.usrActive = user.Active;
//Use this to add the sql user to table named "User"
_dbctx.Users.InsertOnSubmit(sqluser);
//_dbctx.Users.Attach(sqluser);
_dbctx.SubmitChanges();
}