LINQ to SQL語句(10)之Insert

來源:互聯網
上載者:User

標籤:title   onsubmit   關係   product   country   rip   ros   script   address   

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

LINQ to SQL語句(10)之Insert

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.