How to Update with LINQ?

Posted by DaveDev on Stack Overflow See other posts from Stack Overflow or by DaveDev
Published on 2010-06-02T16:22:49Z Indexed on 2010/06/02 16:23 UTC
Read the original article Hit count: 263

Filed under:
|
|
|

currently, I'm doing an update similar to as follows, because I can't see a better way of doing it. I've tried suggestions that I've read in blogs but none work, such as

http://msdn.microsoft.com/en-us/library/bb425822.aspx
and
http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

Maybe these do work and I'm missing some point. Has anyone else had luck with them?

// please note this isn't the actual code. 
// I've modified it to clarify the point I wanted to make 
// and also I didn't want to post our code here!

public bool UpdateMyStuff(int myId, List<int> funds)
{
    // get MyTypes that correspond to the ID I want to update
    IQueryable<MyType> myTypes =
        database.MyTypes.Where(xx => xx.MyType_MyId == myId);

    // delete them from the database
    foreach (db.MyType mt in myTypes)
    {
        database.MyTypes.DeleteOnSubmit(mt);
    }

    database.SubmitChanges();

    // create a new row for each item I wanted to update, and insert it
    foreach (int fund in funds)
    {
        database.MyType mt = new database.MyType
        {
            MyType_MyId = myId,
            fund_id = fund
        };

        database.MyTypes.InsertOnSubmit(mt);
    }

    // try to commit the insert
    try
    {
        database.SubmitChanges();
        return true;
    }
    catch (Exception)
    {
        return false;
        throw;
    }
}

Unfortunately, there isn't a database.MyTypes.Update() method so I don't know a better way to do it. Can sombody suggest what I could do? Thanks.

..as a side note, why isn't there an Update() method?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ