• LINQ to SQL语句(10)之Insert


    插入(Insert)

    1.简单形式

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

    NorthwindDataContext db = newNorthwindDataContext();

    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 = newEmployeeTerritory

    {

    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重写(Overrideusing 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查询。

    这是我所学到的一些知识,在此分享给大家,希望可以帮助到你们。

    以上就是我的分享,新手上道,请多多指教。如果有更好的方法或不懂得地方欢迎在评论区教导和提问喔!

  • 相关阅读:
    jni-03、CMakeLists、gradle配置
    apache 模式、优化、功能 与 nginx优化、应用
    【iptables 实战】07 iptables NAT实验
    STM32(十)------- SPI通信
    【数据增强】图像数据的几种增广方式
    算法训练营 - 贪心
    golang平滑重启库overseer实现原理
    SQL必需掌握的100个重要知识点:使用函数处理数据
    计算机网络 | 第三章 数据链路层 | 王道考研自用笔记
    cesium实战记录(二)三维模式下测量工具的封装
  • 原文地址:https://blog.csdn.net/weixin_57739423/article/details/126577544