- Mastering Entity Framework Core 2.0
- Prabhakaran Anbazhagan
- 314字
- 2021-07-02 21:16:38
Registering the context in services (.NET Core DI)
The dependency injection support in the ASP.NET framework came too late for the .NET developers/architects who were seeking shelter from third-party tools such as Ninject, StructureMap, Castle Windsor, and so on. Finally, we gained support from ASP.NET Core. It has most of the features from the third-party DI providers, but the only difference is the configuration should happen inside the Startup.cs middleware.
First thing's first, let's configure the connection string in our new appSettings.json:
"ConnectionStrings": {
"DefaultConnection": "Server
(localdb)\\mssqllocaldb;Database=MasteringEFCoreBlog;
Trusted_Connection=True;MultipleActiveResultSets=true"
},
Then configure the context as a service (all service configuration goes into Startup.cs). To support that, import MasteringEFCore.Web.Data and Microsoft.EntityFrameworkCore in the Startup class. Finally, add the DbContext to the services collection by creating and including DbContextOptionsBuilder using UseSqlServer():
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<BlogContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("
DefaultConnection")));
services.AddMvc();
}
We will be using a lightweight version of SQL Server called LocalDB for development. This edition was created with the intention of development, so we shouldn't be using it in any other environments. It runs with very minimal configuration, so it's invoked while running the application. The .mdf database file is stored locally.
We have configured the database context using dependency injection, and at this stage, we are good to go. We are almost there. As of now, we have the schema required for the database and the context for EF and services being configured. All of these will end up providing an empty database with literally no values in it. Run the application and see that an empty database is created. It will be of no use. In the next section, let's see how we can seed the database with master data/create tables with sample data, which can be consumed by the application.
- Python Network Programming Cookbook(Second Edition)
- SAS數(shù)據(jù)統(tǒng)計分析與編程實踐
- Java系統(tǒng)化項目開發(fā)教程
- HTML+CSS+JavaScript網(wǎng)頁設(shè)計從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- AMP:Building Accelerated Mobile Pages
- 人人都能開發(fā)RPA機器人:UiPath從入門到實戰(zhàn)
- Java程序設(shè)計實用教程(第2版)
- Java Web開發(fā)教程:基于Struts2+Hibernate+Spring
- 關(guān)系數(shù)據(jù)庫與SQL Server 2012(第3版)
- Visual C++程序設(shè)計全程指南
- HTML5+jQuery Mobile移動應(yīng)用開發(fā)
- Java基礎(chǔ)案例教程(第2版)
- 機器人ROS開發(fā)實踐
- Python Natural Language Processing
- iOS應(yīng)用逆向工程:分析與實戰(zhàn)