在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