LINQ to SQL語句(10)之Insert

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保存到數據庫。ide

2.一對多關係

說明:Category與Product是一對多的關係,提交Category(一端)的數據時,LINQ to SQL會自動將Product(多端)的數據一塊兒提交。spa

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將這些新對象及其關係保存到數據庫。code

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將這些新對象及其關係保持到數據庫。blog

4.使用動態CUD重寫(Override using Dynamic CUD)

說明:CUD就是Create、Update、Delete的縮寫。下面的例子就是新建一個ID(主鍵)爲32的Region,不考慮數據庫中有沒有ID爲32的數據,若是有則替換原來的數據,沒有則插入。ip

Region nwRegion = new Region()
{
    RegionID = 32,
    RegionDescription = "Rainy"
};
db.Regions.InsertOnSubmit(nwRegion);
db.SubmitChanges();

語句描述:使用DataContext提供的分部方法InsertRegion插入一個區域。對SubmitChanges 的調用調用InsertRegion 重寫,後者使用動態CUD運行Linq To SQL生成的默認SQL查詢。get

相關文章
相關標籤/搜索