標籤: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