2010-06-02 4 views
1

В настоящее время я делаю обновление, подобное следующему, потому что я не вижу лучшего способа сделать это. Я попытался предложения, которые я читал в блогах, но ни один работы, такие какКак обновить с помощью 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()?» В основном потому, что если у вас есть другие ожидающие операции (insert/delete), которые влияют на граф объектов, их нужно обрабатывать вместе, поэтому «SubmitChanges()» – RobS

ответ

3

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

Смежные вопросы