views:

9

answers:

2

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.FirstName = 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?

A: 

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.

Randy Minder
This answer is wrong in many way's. First of item2 is a PersonTbl L2S entity even if I use var. Secondly, the whole point of the post is that I want to get rid of item2 entierly.
devzero
A: 

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;
}
devzero