LINQ to SQL update entity that came from client side
I have entity (LONGFORM) that is passed via AJAX to client side. This entity get modified on the client and it's sent back to the server for update in the database. Here's the server side code:
[System.Web.Services.WebMethod()]
public static LONGFOR开发者_StackOverflow中文版M SendDataToClient(int id)
{
DBDataContext _db = new DBDataContext();
LONGFORM _lf = _db.LONGFORMs.SingleOrDefault(l => l.IDLONGFORM == id);
return _lf;
}
[System.Web.Services.WebMethod()]
public static void SaveDataFromClient(LONGFORM _lfFromClient)
{
DBDataContext _db = new DBDataContext();
//_db.LONGFORMs.InsertOnSubmit(_lfFromClient);
_db.LONGFORMs.Attach(_lfFromClient);
_db.SubmitChanges();
}
But I can't "update" the _lfFromClient (LONGFORM) back into the DB! If I use InsertOnSubmit the record will get inserted (despite the fact that LINQ should see that the PK field already exists in the table and thus try an update). If I use the "attach" approach nothing happens.
So, what is the correct way to update an entity that is not related to the current DataContext?
Thanks.-
EDIT: I managed to update the values in LONGFORM adding this line just before SubmitChanges(): _db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, _lfFromClient);
Now the problems is that child entities inside _lfFromClient wont get updated :(
EDIT 2: Ok, I found the solution so here's the answer in hopes it will help someone with the same problem. The trick is to also attach all the child entities because LINQ wont do it automatically. In this example FAMILYMEMBER is a child entity collection of LONGFORM that also gets update on client side. Note the "AttachAll" since LONGFORM -> FAMILYMEMBER is a one to many relation:
[System.Web.Services.WebMethod()]
public static void SaveData(LONGFORM _lfFromClient)
{
DBDataContext _db = new DBDataContext();
_db.LONGFORMs.Attach(_lfFromClient);
_db.FAMILYMEMBERs.AttachAll(_lfFromClient.FAMILYMEMBERs);
_db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, _lfFromClient);
_db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, _lfFromClient.FAMILYMEMBERs);
_db.SubmitChanges();
}
Use:
_db.LONGFORMs.Attach(_lfFromClient, true);
This way you are attaching the entity as modified. See Table.Attach
If this approach gives you any problem, check out this question.
Edit: If you prefer to update the entity with the POSTed data, you can try this:
[System.Web.Services.WebMethod()]
public static void SaveDataFromClient(LONGFORM _lfFromClient)
{
DBDataContext _db = new DBDataContext();
var _lfFromDB = _db.LONGFORMs.Where(l => l.ID == _lfFromClient.ID).FirstOrDefault();
// Update all the properties of _lfFromDB here. For example:
_lfFromDB.Property1 = _lfFromClient.Property1;
_lfFromDB.Property2 = _lfFromClient.Property2;
_db.SubmitChanges();
}
精彩评论