Entity Framework使用DBContext實現(xiàn)增刪改查
有一段時間沒有更新博客了,趕上今天外面下雨,而且沒人約球,打算把最近對Entity Framework DBContext使用的心得梳理一下,早些時候在網上簡單查過,對于最新版本的EF并沒有類似的知識梳理類文章,希望對大家有所幫助。
1. 不要Code first, 也不要DB first
我為什么討厭Code first和DB first呢?首先Code first是先寫代碼,數據庫完全由代碼生成,開發(fā)階段尚可,一旦到了產品發(fā)布階段,如果需要添加字段,我們總不能用 visual studio去生產環(huán)境上去更新數據庫吧,聽起來就很可怕。而且另外的一個問題自動是生成的數據庫腳本也不可控,還不如自己提前設計好。DB first也好不了哪去,反向轉過來的代碼包含很多沒有用的文件,而且數據庫的更新還要重新走Model生成過程,簡直無法理解為什么會有這樣的設計。說了這么多,怎么解決呢?
數據庫和領域模型分開設計,按照對應關系映射字段,使用自定義鏈接字串,既不使用領域模型生成數據庫,也不用數據庫生成領域模型,示例代碼如下,SQL Code 以 Destinations和TTable表為例:
CREATE TABLE [DBO].[Destinations] ( [DestinationId] [int] PRIMARY KEY NOT NULL, [Name] [nvarchar](max) NULL, [Country] [nvarchar](max) NULL, [Description] [nvarchar](max) NULL, [Photo] [varbinary](max) NULL
CREATE TABLE [TTT].[TTable] ( [Id] [int] PRIMARY KEY NOT NULL, [Name] [nvarchar](max) NULL )
Model Class:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class Destination { public int DestinationId { get; set; } public string Name { get; set; } public string Country { get; set; } public string Description { get; set; } public byte[] Photo { get; set; } public List<Lodging> Lodgings { get; set; } } public class Lodging { public int LodgingId { get; set; } public string Name { get; set; } public string Owner { get; set; } public bool IsResort { get; set; } public Destination Destination { get; set; } } public class TTable { public int Id { get; set; } public string Name { get; set; } } }
Connect String:
<connectionStrings> <add name="BAContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DataAccess.BreakAwayContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" /> </connectionStrings>
DB Context:
using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using Model; namespace DataAccess { public class TTableConfiguration : EntityTypeConfiguration<TTable> { public TTableConfiguration() { this.ToTable("TTable", "TTT"); } } public class BreakAwayContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new TTableConfiguration()); } public BreakAwayContext(string connString) : base(connString) { } public DbSet<Destination> Destinations { get; set; } public DbSet<Lodging> Lodgings { get; set; } public DbSet<TTable> TTables { get; set; } } }
2. 如果數據庫的表的字段和領域模型的字段不對應,如何處理呢?比如本文的TTable表是在TTT Schema下面的, 而其他表示設計在DBO下面,最方便的方式是使用fluent API, 具體代碼如請參見 TTableConfiguration Class和 OnModelCreating()方法,可配置的粒度非常細,比如可以配置領域模型和數據庫的哪個Schema的哪張表的哪一列對應,本文是將TTable 類的數據庫表配置為了TTT Schema下的TTable表,
public class TTableConfiguration : EntityTypeConfiguration<TTable> { public TTableConfiguration() { this.ToTable("TTable", "TTT"); } }
3. 增刪該查自帶事物支持,具體代碼如下,
public static int Insert() { var destination = new Destination { Country = "Chs", Description = "Chs is the language package", Name = "xsss" }; using (var context = new BreakAwayContext(ConfigurationManager.ConnectionStrings["BAContext"].ConnectionString)) { var rt = context.Destinations.Add(destination); context.SaveChanges(); return rt.DestinationId; } } public static void Update(Destination destIn) { using (var context = new BreakAwayContext(ConfigurationManager.ConnectionStrings["BAContext"].ConnectionString)) { var dest = context.Destinations.Where(a => a.DestinationId == destIn.DestinationId).Single(); dest.Name = destIn.Name; context.SaveChanges(); } } public static void Delete(int destId) { using (var context = new BreakAwayContext(ConfigurationManager.ConnectionStrings["BAContext"].ConnectionString)) { var destination = new Destination() { DestinationId = destId }; context.Destinations.Attach(destination); context.Destinations.Remove(destination); context.SaveChanges(); } } public static Destination Query(int destId) { using (var context = new BreakAwayContext(ConfigurationManager.ConnectionStrings["BAContext"].ConnectionString)) { IQueryable<Destination> dest = context.Destinations.Where(a => a.DestinationId == destId); return dest.Single(); } }
4. 如果需要多個操作同時成功或者失敗,需要手動開啟事務,具體代碼如下,
public static void TransactionOps() { using (var context = new BreakAwayContext(ConfigurationManager.ConnectionStrings["BAContext"].ConnectionString)) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { var destination = new Destination { Country = "Chs", Description = "Chs is the language package", Name = "xs2s" }; var destId = context.Destinations.Add(destination); context.SaveChanges(); context.Destinations.Attach(destId); context.Destinations.Remove(destId); context.SaveChanges(); dbContextTransaction.Commit(); } catch (System.Exception ex) { dbContextTransaction.Rollback(); System.Console.WriteLine(ex.ToString()); } } } }
5. 分頁查詢是網站設計的常用功能,一個簡單的真分頁查詢方法如下如下所示,
public static List<Destination> QueryPaging<TKey>(int pageIndex, int pageSize, Expression<Func<Destination, bool>> whereLambda, Expression<Func<Destination, TKey>> orderBy) { using (var context = new BreakAwayContext(ConfigurationManager.ConnectionStrings["BAContext"].ConnectionString)) { return context.Destinations.Where(whereLambda).OrderBy(orderBy).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } }
總結
本文對最新版本的Entity Framework進行增刪改查操作給出了詳盡的解釋,并且給出了數據庫和領域模型代碼分開設計的完整解決方案,同時介紹了手動數據庫表和領域模型映射,數據庫事務實現(xiàn),分頁查詢等常用功能,希望對大家有所幫助。
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章:
1. AJAX實現(xiàn)數據的增刪改查操作詳解【java后臺】2. 使用idea開發(fā)javaWeb應用程序的思路(實現(xiàn)用戶的增刪改查)3. Java實現(xiàn)RedisUtils操作五大集合(增刪改查)4. Python+Django+MySQL實現(xiàn)基于Web版的增刪改查的示例代碼5. Java springboot Mongodb增刪改查代碼實例6. Springboot+Bootstrap實現(xiàn)增刪改查實戰(zhàn)7. JS?中數組的增刪改查和對象的增刪改查實例詳解8. ASP.NET MVC使用Identity增刪改查用戶9. Python接入MySQL實現(xiàn)增刪改查的實戰(zhàn)記錄10. python使用openpyxl庫讀寫Excel表格的方法(增刪改查操作)
