LINQ to SQL語句(10)之Insert
系列文章導航:
LINQ to SQL語句(2)之Select/Distinct
LINQ to SQL語句(3)之Count/Sum/Min/Max/Avg
LINQ to SQL語句(6)之Group By/Having
LINQ to SQL語句(7)之Exists/In/Any/All/Contains
LINQ to SQL語句(8)之Concat/Union/Intersect/Except
LINQ to SQL語句(9)之Top/Bottom和Paging和SqlMethods
LINQ to SQL語句(12)之Delete和使用Attach
LINQ to SQL語句(14)之Null語義和DateTime
LINQ to SQL語句(19)之ADO.NET與LINQ to SQL
插入(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查詢。