本節,直接寫通過代碼來學習。這些基本操作都比較簡單,與這些基本操作相關的內容在之前的1至6節基本介紹完畢。
l 增加:
方法1:使用AddToXXX(xxx)方法:實例代碼如下:
using (var edm = new NorthwindEntities())
{
Customers c = new Customers { CustomerID = "c#", City = "成都市", Address = "中國四川省", CompanyName = "cnblogs", Country = "中國", Fax = "10086", Phone = "1008611", PostalCode = "610000", Region = "天府廣場", ContactName = "風車車.Net" };
edm.AddToCustomers(c);
int result = edm.SaveChanges();
Assert.AreEqual (result, 1);
Customers addc = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c#");
Console.WriteLine("CustomerId={0},City={1}", addc.CustomerID, addc.City);
}
方法2:使用ObjectContext的AddObject(string entitySetName, object entity)方法。實例代碼如下:
using (var edm = new NorthwindEntities())
{
Customers c = new Customers { CustomerID = "c2", City = "成都市2", Address = "中國四川省2", CompanyName = "cnblogs", Country = "中國", Fax = "10086", Phone = "1008611", PostalCode = "610000", Region = "天府廣場", ContactName = "風車車.Net" };
edm.AddObject("Customers", c);
int result = edm.SaveChanges();
Assert.AreEqual (result, 1);
Customers addc = edm.Customers.FirstOrDefault(cc => cc.CustomerID == "c2");
Console.WriteLine("CustomerId={0},City={1}", addc.CustomerID, addc.City);
}