`
bolutes
  • 浏览: 869745 次
文章分类
社区版块
存档分类
最新评论

LINQ之使用Attach更新和删除(Update and Delete with Attach)

 
阅读更多

说明:在不同的DataContext中,实现插入、更新、删除。看下面的一个例子:

//通常,通过从其他层反序列化XML获取要附加的实体
//此示例使用 LoadWith 在一个查询中预先加载客户和订单,
//并禁用延迟加载
Customer cust = null;
using (NorthwindDataContext tempdb = new NorthwindDataContext())
{
    DataLoadOptions shape = new DataLoadOptions();
    shape.LoadWith<Customer>(c => c.Orders);
    //加载第一个客户实体及其订单
    tempdb.LoadOptions = shape;
    tempdb.DeferredLoadingEnabled = false;
    cust = tempdb.Customers.First(x => x.CustomerID == "ALFKI");
}
Order orderA = cust.Orders.First();
Order orderB = cust.Orders.First(x => x.OrderID > orderA.OrderID);
using (NorthwindDataContext db2 = new NorthwindDataContext())
{
    //将第一个实体附加到当前数据上下文,以跟踪更改
    db2.Customers.Attach(cust);
    //附加相关订单以进行跟踪; 否则将在提交时插入它们
    db2.Orders.AttachAll(cust.Orders.ToList());
    //更新客户的Phone.
    cust.Phone = "2345 5436";
    //更新第一个订单OrderA的ShipCity.
    orderA.ShipCity = "Redmond";
    //移除第二个订单OrderB.
    cust.Orders.Remove(orderB);
    //添加一个新的订单Order到客户Customer中.
    Order orderC = new Order() { ShipCity = "New York" };
    cust.Orders.Add(orderC);
    //提交执行
    db2.SubmitChanges();
}

语句描述:从一个上下文提取实体,并使用 Attach 和 AttachAll 附加来自其他上下文的实体,然后更新这两个实体,删除一个实体,添加另一个实体。更改被提交到数据库。

摘自:http://www.cnblogs.com/lyj/archive/2008/01/28/1056133.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics