zoukankan      html  css  js  c++  java
  • LINQ to SQL语句(10)之Insert

    1.简单形式

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

    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查询。

  • 相关阅读:
    hdu 1108 最小公倍数
    hdu 1106 排序
    hdu 1097 A hard puzzle
    hdu 1076 An Easy Task
    hdu 1064 Financial Management
    hdu 1061 Rightmost Digit
    hdu 1050 Moving Tables
    hdu 1060 Leftmost Digit
    hdu 1049 Climbing Worm
    hdu1104
  • 原文地址:https://www.cnblogs.com/SuperMetalMax/p/6210039.html
Copyright © 2011-2022 走看看