• LINQ to SQL语句之Insert/Update/Delete操作


    Insert/Update/Delete操作

    插入(Insert)

    1.简单形式

    说明:new一个对象,使用InsertOnSubmit方法将其加入到对应的集合中,使用SubmitChanges()提交到数据库。

    NorthwindDataContext db = new NorthwindDataContext();
    var newCustomer = new Customer
    {
        CustomerID = "MCSFT",
        CompanyName = "Microsoft",
        ContactName = "John Doe",
        ContactTitle = "Sales Manager",
        Address = "1 Microsoft Way",
        City = "Redmond",
        Region = "WA",
        PostalCode = "98052",
        Country = "USA",
        Phone = "(425) 555-1234",
        Fax = null
    };
    db.Customers.InsertOnSubmit(newCustomer);
    db.SubmitChanges();

    语句描述:使用InsertOnSubmit方法将新客户添加到Customers 表对象。调用SubmitChanges 将此新Customer保存到数据库。

    2.一对多关系

    说明:Category与Product是一对多的关系,提交Category(一端)的数据时,LINQ to SQL会自动将Product(多端)的数据一起提交。

    var newCategory = new Category
    {
        CategoryName = "Widgets",
        Description = "Widgets are the ……"
    };
    var newProduct = new Product
    {
        ProductName = "Blue Widget",
        UnitPrice = 34.56M,
        Category = newCategory
    };
    db.Categories.InsertOnSubmit(newCategory);
    db.SubmitChanges();

    语句描述:使用InsertOnSubmit方法将新类别添加到Categories表中,并将新Product对象添加到与此新Category有外键关系的Products表中。调用SubmitChanges将这些新对象及其关系保存到数据库。

    3.多对多关系

    说明:在多对多关系中,我们需要依次提交。

    var newEmployee = new Employee
    {
        FirstName = "Kira",
        LastName = "Smith"
    };
    var newTerritory = new Territory
    {
        TerritoryID = "12345",
        TerritoryDescription = "Anytown",
        Region = db.Regions.First()
    };
    var newEmployeeTerritory = new EmployeeTerritory
    {
        Employee = newEmployee,
        Territory = newTerritory
    };
    db.Employees.InsertOnSubmit(newEmployee);
    db.Territories.InsertOnSubmit(newTerritory);
    db.EmployeeTerritories.InsertOnSubmit(newEmployeeTerritory);
    db.SubmitChanges();

    语句描述:使用InsertOnSubmit方法将新雇员添加到Employees 表中,将新Territory添加到Territories表中,并将新EmployeeTerritory对象添加到与此新Employee对象和新Territory对象有外键关系的EmployeeTerritories表中。调用SubmitChanges将这些新对象及其关系保持到数据库。

    4.使用动态CUD重写(Override using Dynamic CUD)

    说明:CUD就是Create、Update、Delete的缩写。下面的例子就是新建一个ID(主键)为32的Region,不考虑数据库中有没有ID为32的数据,如果有则替换原来的数据,没有则插入。

    Region nwRegion = new Region()
    {
        RegionID = 32,
        RegionDescription = "Rainy"
    };
    db.Regions.InsertOnSubmit(nwRegion);
    db.SubmitChanges();

    语句描述:使用DataContext提供的分部方法InsertRegion插入一个区域。对SubmitChanges 的调用调用InsertRegion 重写,后者使用动态CUD运行Linq To SQL生成的默认SQL查询。

    更新(Update)

    说明:更新操作,先获取对象,进行修改操作之后,直接调用SubmitChanges()方法即可提交。注意,这里是在同一个DataContext中,对于不同的DataContex看下面的讲解。

    1.简单形式

    Customer cust =
        db.Customers.First(c => c.CustomerID == "ALFKI");
    cust.ContactTitle = "Vice President";
    db.SubmitChanges();

    语句描述:使用SubmitChanges将对检索到的一个Customer对象做出的更新保持回数据库。

    2.多项更改

    var q = from p in db.Products
            where p.CategoryID == 1
            select p;
    foreach (var p in q)
    {
        p.UnitPrice += 1.00M;
    }
    db.SubmitChanges();

    语句描述:使用SubmitChanges将对检索到的进行的更新保持回数据库。

    删除(Delete)

    1.简单形式

    说明:调用DeleteOnSubmit方法即可。

    OrderDetail orderDetail =
        db.OrderDetails.First
        (c => c.OrderID == 10255 && c.ProductID == 36);
    db.OrderDetails.DeleteOnSubmit(orderDetail);
    db.SubmitChanges();

    语句描述:使用DeleteOnSubmit方法从OrderDetail 表中删除OrderDetail对象。调用SubmitChanges 将此删除保持到数据库。

    2.一对多关系

    说明:Order与OrderDetail是一对多关系,首先DeleteOnSubmit其OrderDetail(多端),其次DeleteOnSubmit其Order(一端)。因为一端是主键。

    var orderDetails =
        from o in db.OrderDetails
        where o.Order.CustomerID == "WARTH" &&
        o.Order.EmployeeID == 3
        select o;
    var order =
        (from o in db.Orders
         where o.CustomerID == "WARTH" && o.EmployeeID == 3
         select o).First();
    foreach (OrderDetail od in orderDetails)
    {
        db.OrderDetails.DeleteOnSubmit(od);
    }
    db.Orders.DeleteOnSubmit(order);
    db.SubmitChanges();

    语句描述语句描述:使用DeleteOnSubmit方法从Order 和Order Details表中删除Order和Order Detail对象。首先从Order Details删除,然后从Orders删除。调用SubmitChanges将此删除保持到数据库。

    3.推理删除(Inferred Delete)

    说明:Order与OrderDetail是一对多关系,在上面的例子,我们全部删除CustomerID为WARTH和EmployeeID为3 的数据,那么我们不须全部删除呢?例如Order的OrderID为10248的OrderDetail有很多,但是我们只要删除ProductID为11的OrderDetail。这时就用Remove方法。

    Order order = db.Orders.First(x => x.OrderID == 10248);
    OrderDetail od = 
        order.OrderDetails.First(d => d.ProductID == 11);
    order.OrderDetails.Remove(od);
    db.SubmitChanges();

    语句描述语句描述:这个例子说明在实体对象的引用实体将该对象从其EntitySet 中移除时,推理删除如何导致在该对象上发生实际的删除操作。仅当实体的关联映射将DeleteOnNull设置为true且CanBeNull 为false 时,才会发生推理删除行为。

    使用Attach更新(Update with Attach)

    说明:在对于在不同的DataContext之间,使用Attach方法来更新数据。例如在一个名为tempdb的NorthwindDataContext中,查询出Customer和Order,在另一个NorthwindDataContext中,Customer的地址更新为123 First Ave,Order的CustomerID 更新为CHOPS。

    //通常,通过从其他层反序列化 XML 来获取要附加的实体
    //不支持将实体从一个DataContext附加到另一个DataContext
    //因此若要复制反序列化实体的操作,将在此处重新创建这些实体
    Customer c1;
    List<Order> deserializedOrders = new List<Order>();
    Customer deserializedC1;
    using (NorthwindDataContext tempdb = new NorthwindDataContext())
    {
        c1 = tempdb.Customers.Single(c => c.CustomerID == "ALFKI");
        deserializedC1 = new Customer
        {
            Address = c1.Address,
            City = c1.City,
            CompanyName = c1.CompanyName,
            ContactName = c1.ContactName,
            ContactTitle = c1.ContactTitle,
            Country = c1.Country,
            CustomerID = c1.CustomerID,
            Fax = c1.Fax,
            Phone = c1.Phone,
            PostalCode = c1.PostalCode,
            Region = c1.Region
        };
        Customer tempcust =
            tempdb.Customers.Single(c => c.CustomerID == "ANTON");
        foreach (Order o in tempcust.Orders)
        {
            deserializedOrders.Add(new Order
            {
                CustomerID = o.CustomerID,
                EmployeeID = o.EmployeeID,
                Freight = o.Freight,
                OrderDate = o.OrderDate,
                OrderID = o.OrderID,
                RequiredDate = o.RequiredDate,
                ShipAddress = o.ShipAddress,
                ShipCity = o.ShipCity,
                ShipName = o.ShipName,
                ShipCountry = o.ShipCountry,
                ShippedDate = o.ShippedDate,
                ShipPostalCode = o.ShipPostalCode,
                ShipRegion = o.ShipRegion,
                ShipVia = o.ShipVia
            });
        }
    }
    using (NorthwindDataContext db2 = new NorthwindDataContext())
    {
        //将第一个实体附加到当前数据上下文,以跟踪更改
        //对Customer更新,不能写错
        db2.Customers.Attach(deserializedC1);
        //更改所跟踪的实体
        deserializedC1.Address = "123 First Ave";
        //附加订单列表中的所有实体
        db2.Orders.AttachAll(deserializedOrders);
        //将订单更新为属于其他客户
        foreach (Order o in deserializedOrders)
        {
            o.CustomerID = "CHOPS";
        }
        //在当前数据上下文中提交更改
        db2.SubmitChanges();
    }

    语句描述:从另一个层中获取实体,使用Attach和AttachAll将反序列化后的实体附加到数据上下文,然后更新实体。更改被提交到数据库。

    使用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

    冯瑞涛
  • 相关阅读:
    Mac上安装Git
    原型对象和原型链
    ES6入门
    一边宽度固定,一边宽度自适应
    15种css居中方式
    阿里CDN核心技术解密
    尽量用const,enum,inline代替define
    Nginx安装
    百度笔试题:malloc/free与new/delete的区别(转)
    C++内存管理(转)
  • 原文地址:https://www.cnblogs.com/finehappy/p/1654977.html
Copyright © 2020-2023  润新知