在asp.net core中配置SqlSugar,DI,Configure,sqlite


先來看基於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 = ""

            });
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM