說明: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保存到數據庫。
說明: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將這些新對象及其關系保存到數據庫。
說明:在多對多關系中,我們需要依次提交。
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將這些新對象及其關系保持到數據庫。
說明: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查詢。