LINQ to SQL语句(10)之Insert

LINQ to SQL语句(10)之Insert

插入(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查询

posted @ 2012-03-06 11:21  ^_^漂……  阅读(191)  评论(0编辑  收藏  举报