首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用LINQ更新?

如何使用LINQ更新?
EN

Stack Overflow用户
提问于 2010-06-03 00:22:50
回答 1查看 197关注 0票数 1

目前,我正在进行类似如下的更新,因为我看不到更好的方法。我尝试了我在博客中读到的建议,但都没有效果,比如

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

也许这些确实有效,但我还是漏掉了一些要点。还有没有其他人有运气呢?

代码语言:javascript
运行
复制
// 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()方法呢?

EN

Stack Overflow用户

回答已采纳

发布于 2010-06-03 00:34:56

嗯?

代码语言:javascript
运行
复制
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();
  }
}
票数 3
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2959573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档