在.NetCore控制台下用注入模式访问数据库

直接上代码:

Program.cs

private static readonly IConfigurationBuilder Configuration = new ConfigurationBuilder();
private static IConfigurationRoot _configuration;
private static SqlDBContext _dbContext;//数据库访问的DBContext
public static void Main(string[] args)
{
 _configuration = Configuration.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddEnvironmentVariables().Build();
            var serviceCollection = new ServiceCollection()
                .AddDbContextPool(options =>
                    {
                        options.UseSqlServer(_configuration.GetConnectionString("check"), //读取配置文件中的链接字符串
                        b => b.UseRowNumberForPaging());
                    })
                .AddTransient()                
                .AddOptions();
            var provider = serviceCollection.BuildServiceProvider();
           _dbContext = provider.GetService();
           //下面可以写注入DBContext的代码了
            AreasDAL areasDAL=new AreasDAL(_dbContext);
}

AreasDAL 

public class AreasDAL
{
    private SqlDBContext.SqlDBContext _sqlDBContext;
    public AreasDAL(SqlDBContext.SqlDBContext sqlDBContext)
        {
            _sqlDBContext = sqlDBContext;
        }
    //下面是实际操作访问数据库操作代码
}

SqlDBContext

public class SqlDBContext : DbContext
{
    public SqlDBContext(DbContextOptions options) : base(options)
     {

     }
    public DbSet DbAreas { get; set; }
}

 

你可能感兴趣的:(C#)