在線場景中保存實體數據是一項至關容易的任務,由於使用的是同一個context,這個context會自動跟蹤全部實體發生的更改。html
下圖說明了在線場景中的CUD(建立,更新,刪除)操做。sql
EF在調用context.SaveChange方法時,根據EntityState進行添加、修改或刪除實體實例,並執行INSERT,UPDATE和DELETE語句。在線場景中,context跟蹤全部實體的實例,EntityState不管什麼時候建立,修改或刪除實體,它都會自動爲每一個實體設置適當的實例。數據庫
使用DbSet.Add方法將新實體添加到上下文(context),調用context.SaveChanges()方法時在數據庫中插入新記錄。ide
using (var context = new SchoolDBEntities()) { var std = new Student() { FirstName = "Bill", LastName = "Gates" }; context.Students.Add(std); context.SaveChanges(); }
在上面的示例中,context.Students.Add(std)將新建立的Student實體實例,這個新實例的EntityState 爲Added。調用context.SaveChanges()方法時數據庫構建並執行如下INSERT語句。post
exec sp_executesql N'INSERT [dbo].[Students]([FirstName], [LastName]) VALUES (@0, @1) SELECT [StudentId] FROM [dbo].[Students] WHERE @@ROWCOUNT > 0 AND [StudentId] = scope_identity()',N ''@0 nvarchar(max) ,@1 nvarchar(max) ',@0=N'Bill',@1=N'Gates' go
在線場景中,EF API會跟蹤上下文中全部實體。所以,在編輯實體數據時,EF會自動標記EntityState爲Modified,在調用SaveChanges()方法時在數據庫中生成並執行更新的語句。spa
using (var context = new SchoolDBEntities()) { var std = context.Students.First<Student>(); std.FirstName = "Steve"; context.SaveChanges(); }
咱們使用從數據庫中檢索第一個學生:context.Students.First<student>()。一旦咱們修改了FirstName,上下文就會將實例的EntityState設置爲Modified。當咱們調用該SaveChanges()方法時,會在數據庫中構建並執行如下Update語句。3d
exec sp_executesql N'UPDATE [dbo].[Students] SET [FirstName] = @0 WHERE ([StudentId] = @1)', N'@0 nvarchar(max) ,@1 int',@0=N'Steve',@1=2 Go
在更新語句中,EF API經過主鍵找到要修改的實例,修改時僅包含修改的屬性,其餘屬性將被忽略。在上面的示例中,僅FirstName編輯了屬性,所以update語句中只包含FirstName列。code
DbSet.Remove()方法用於刪除數據庫表中的記錄。htm
using (var context = new SchoolDBEntities()) { var std = context.Students.First<Student>(); context.Students.Remove(std); context.SaveChanges(); }
context.Students.Remove(std)將std實體對象標記爲Deleted。所以,EF將在數據庫中構建並執行如下DELETE語句。對象
exec sp_executesql N'DELETE [dbo].[Students] WHERE ([StudentId] = @0)',N'@0 int',@0=1 Go
經過上邊的例子能夠看出,在線場景中添加,更新或刪除中的數據很是容易。
EF系列目錄連接:Entity Franmework系列教程彙總