先來看基於SqlSugar數據庫上下文的定義
namespace MyStart { public class IXDbContext { public IXDbContext(IConfiguration cfg) { Db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = cfg.GetConnectionString("dbc1"), DbType = DbType.Sqlite, IsAutoCloseConnection = true }); } public SqlSugarClient Db;//用來處理事務多表查詢和復雜的操作 public DbSet<Links> Links { get { return new DbSet<Links>(Db); } } public DbSet<MyAccounts> MyAccounts { get { return new DbSet<MyAccounts>(Db); } } } }
在這里,我如果把Links的定義和DbSet的定義寫出來的話,肯定就啰嗦了,想要了解的話,請去sqlsugar官網查看就行,各種復制 實在沒必要。See 官網文檔
現在把它注入到DI系統中並配置。
public void ConfigureServices(IServiceCollection services) { services.AddMvc();//增加mvc支持 services.AddTransient<MyStart.IXDbContext>(); services.Configure<IConfiguration>(Configuration); services.AddSession(); }
現在就用它來做點愛做的事情吧,比如,插入幾條數據,我就在config里面做了。
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); DbInit.InitializeAsync(app); //IdentitySeedData.EnsurePopulated(app);//初始化數據庫 }
對,一開始是在這里寫的,后來放到一個靜態方法里去了。
public static class DbInit { public static void InitializeAsync(IApplicationBuilder app) { var db = app.ApplicationServices.GetRequiredService<MyStart.IXDbContext>(); db.Links.Insert(new MyStart.Models.Links { Category = "前台開發", LinkID = Guid.NewGuid(), Title = "開源中國", URL = "http://www.oschina.net", memo = "" }); } }