1.关系型数据库
如果是关系型数据库,则用以下方式连接
关系型数据库用EF的话直接在ConfigureServices里面配置以下,请看加粗的部分,读取配置文件中的DB连接字符串
public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.AddDbContext<MvcMovieContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyBBS")));
}
2.NOSQL,比如MongoDB
替换为如下代码,且MoviesDatabaseSettings即为配置文件中的DB连接信息
services.Configure<MoviesDatabaseSettings>(Configuration.GetSection(nameof(MoviesDatabaseSettings))); services.AddSingleton<IMoviesDatabaseSettings>(sp => sp.GetRequiredService<IOptions<MoviesDatabaseSettings>>().Value);
此外还需要添加一个services来做处理,使用的时候连接到MongoDB,因为NOSQL没有类似SQL Server一样,有EF框架做支撑
public MoviesService(IMoviesstoreDatabaseSettings settings) { //连接数据库服务 var client = new MongoClient(settings.ConnectionString); var database = client.GetDatabase(settings.DatabaseName); _movies = database.GetCollection<Book>(settings.MoviesCollectionName); }