I get a LINQ object from MVC2 that I want to update to the database. My current code looks like this:
public PersonTbl Save(PersonTbl item)
{
if (item.ID == 0) //new item
{
_dbContext.PersonTbls.InsertOnSubmit(item);
}
else
{
var item2 = _dbContext.PersonTbls.Single(i => i.ID == item.ID);
item2.LastName = item.LastName;
item2.FirstN开发者_JS百科ame = item.FirstName;
item2.MobilePhone = item.MobilePhone;
}
_dbContext.SubmitChanges();
return item;
}
What I'm basically wondering is why there is no UpdateOnSubmit(item) function. Is it any way I can solve this another way?
I found the answer in attatch:
/// <summary>
/// This function inserts or updates an item
/// </summary>
/// <param name="newPerson">This item will be inserted or updated in the database</param>
/// <returns>Returns the updated version of the object.</returns>
public PersonTbl Save(PersonTbl newPerson)
{
if (newPerson.ID == 0) //new item
{
_dbContext.PersonTbls.InsertOnSubmit(newPerson);
}
else
{
_dbContext.PersonTbls.Attach(newPerson);
_dbContext.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, newPerson);
}
_dbContext.SubmitChanges();
return newPerson;
}
I would say that you have no UpdateOnSubmit() method because item2 is an anonymous type, not a L2S class. If you cast item2 to a PersonTbl L2S entity, you should be fine.
精彩评论