Original: Working with SQL Server LocalDB
Rick Anderson
Translation: Chinese (initial)
Proofreading: Meng Liang (book Edge), Shuo Zhang (Apple), Huden (Seay)
ApplicationDbContext
Class is responsible for connecting to the database and Movie
mapping objects and data records. Startup.cs file, the database context is ConfigureServices
registered with the Dependency injection container in the method.
// This method gets called by the runtime. Use this method to add services to the container.publicvoidConfigureServices(IServiceCollection services){ // Add framework services. services.AddDbContext//手动高亮 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"//手动高亮
The ASP. NET Core Configuration system reads ConnectionString
. In local development mode, it gets the connection string from the appsettings. json file.
{ "ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-7db2893b-375e-48bd-86a3-bb9779b72ebe;Trusted_Connection=True;MultipleActiveResultSets=true" //手动高亮 }, "Logging": { "IncludeScopes": false,
When you deploy an application to a test server or a production server, you can use environment variables or another method to set the connection string for the actual SQL Server database. More reference Configuration.
SQL Server Express LocalDB
LocalDB is a lightweight version of the SQL Server Express Database engine used in the program development phase. Because LocalDB is started and executed in user mode, it does not have a complex configuration. By default, the "*.mdf" file created by the LocalDB database is in the c:/users/<user> directory.
From the View menu, open SQL Server Objects Explorer (SQL Server Object Explorer , (Ssox)).
Right Movie
-click Table > View Designer (View Designer)
Note the key icon behind the ID
. By default, EF will name ID
the property as the primary key.
- Right-click the
Movie
table > View Data
Populating the Database
Create a new class named in the Models folder SeedData
. Replace the generated code with the following code.
usingMicrosoft.Entityframeworkcore;usingMicrosoft.Extensions.dependencyinjection;usingMvcmovie.Data;usingSystem;usingSystem.Linq;namespaceMvcmovie.Models{ Public Static classSeeddata { Public Static void Initialize(IServiceProvider serviceprovider) {using(varContext =New Applicationdbcontext(ServiceProvider.Getrequiredservice<DbContextOptions<ApplicationDbContext>> ())) {if(Context.Movie. any()) {return;//DB has been seeded} context.Movie.AddRange(NewMovie {Title ="When Harry Met Sally", ReleaseDate = DateTime.Parse("1989-1-11"), Genre ="Romantic comedy", Price =7.99M},NewMovie {Title ="Ghostbusters", ReleaseDate = DateTime.Parse("1984-3-13"), Genre ="Comedy", Price =8.99M},NewMovie {Title ="Ghostbusters 2", ReleaseDate = DateTime.Parse("1986-2-23"), Genre ="Comedy", Price =9.99M},NewMovie {Title ="Rio Bravo", ReleaseDate = DateTime.Parse("1959-4-15"), Genre ="Western", Price =3.99M}); Context.SaveChanges(); } } }}
Note that if movies exists in the database context, the fill initializer is returned.
if (context.Movie.Any()) { return; // DB has been seeded //手动高亮 }
The method in the Startup. cs file Configure
finally adds a fill initializer.
app.UseMvc(routes => { routes.MapRoute( "default", "{controller=Home}/{action=Index}/{id?}"); }); SeedData.Initialize(app.ApplicationServices//手动高亮}
Test the application
- Deletes all records in the database. You can do this directly in the browser by clicking the Delete link or in Ssox (SQL Server Object Explorer).
- Forces the application to initialize (
Startup
calling a method in the class) so that the Fill method runs automatically. In order to force the initialization, IIS Express must first stop and then restart. It can be implemented in any of the following ways:
Attention
If the database is not initialized, if (context.Movie.Any())
set breakpoints in this line and start debugging
The application displays the data that is populated.
Back to Catalog
Reference page:
Http://www.yuanjiaocheng.net/entity/dbentityentry-class.html
Http://www.yuanjiaocheng.net/Jsp/first.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-actionresults.html
Http://www.yuanjiaocheng.net/CSharp/csharp-delegate.html
Http://www.yuanjiaocheng.net/webapi/create-crud-api-1.html
Http://www.yuanjiaocheng.net/webapi/first.html
Http://www.yuanjiaocheng.net/mvc/mvc-helper-RadioButton.html
Http://www.yuanjiaocheng.net/mvc/mvc-controller.html
Http://www.yuanjiaocheng.net/entity/modelbrowser.html
Http://www.yuanjiaocheng.net/mvc/mvc-architecture.html
Http://www.yuanjiaocheng.net/Linq/linq-api.html
ASP. NET Core Chinese Document Chapter II Guide (4.5) using SQL Server LocalDB