tags:

views:

79

answers:

2

Hi,

I am using Linq2Sql and trying to update a table.

But no update happens when I try to update a column.

I have tried it with the attach statement but then I get a duplicate key error.

I am using my own entity and copying it over to the context entity as you can see.

Is that my problem?

This is my save method.

   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();
    }

This is my test method.

[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");
}
A: 

I am using my own entity and copying it over to the context entity as you can see.

Is that my problem?

Yes, this wrecks the DataContexts identity map (used for entity tracking). The easiest way to update is approximately:

User user = _dbctx.Users.Single(u => u.usrID == 1474);
user.FirstName = "TestXXXX";
_dbctx.SubmitChanges();
Jason
A: 

Before Submitting changes, you should add statement "dbcontext.tablename.InserOnSubmit(object);" method.

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();
    }
H Sampat