如何使用LINQ进行更新?

问题描述:

目前,我正在进行类似如下的更新,因为我看不到更好的方法。我已经试过了我的博客,但没有工作读过的建议,如如何使用LINQ进行更新?

http://msdn.microsoft.com/en-us/library/bb425822.aspx

http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx

也许这些做的工作,我错过了一些点。有没有其他人与他们运气?

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

不幸的是,没有database.MyTypes.Update()方法,所以我不知道更好的方法来做到这一点。辛博迪可以提出我能做些什么?谢谢。

..作为一个附注,为什么没有Update()方法?

+0

“..作为备注,为什么没有Update()方法?”主要是因为如果你有其他待处理操作(插入/删除)影响对象图形,它们需要一起处理,因此“SubmitChanges()” – RobS 2010-06-02 16:28:22

Eh?

public void UpdateCustomer(int CustomerId, string CustomerName) 
{ 
    using (MyDataContext dc = new MyDataContext) 
    { 
    //retrieve an object from the datacontext. 
    // datacontext tracks changes to this instance!!! 
    Customer customer = dc.Customers.First(c => c.ID = CustomerId); 
    // property assignment is a change to this instance 
    customer.Name = CustomerName; 
    //dc knows that customer has changed 
    // and makes that change in the database 
    dc.SubmitChanges(); 
    } 
} 
+0

花了很长时间让我标记为正确!但该项目至今一直搁置。感谢您的意见 – DaveDev 2011-02-09 09:52:30