官术网_书友最值得收藏!

Creating and seeding databases

We have created an empty database, and we should have a mechanism by which we can seed the initial/master data that might be required by the web application. In our case, we don't have any master data, so all we can do is create a couple of blogs and corresponding posts. We need to ensure whether the database was created or not before we start adding data to it. The EnsureCreated method helps us in verifying this. Create a new DbInitializer.cs class file inside the Data folder and include the following code:

    public static void Initialize(BlogContext context)
{
context.Database.EnsureCreated();
// Look for any blogs.
if (context.Blogs.Any())
{
return; // DB has been seeded
}
var dotnetBlog = new Blog {
Url = "http://blogs.packtpub.com/dotnet" };
var dotnetCoreBlog = new Blog { Url =
"http://blogs.packtpub.com/dotnetcore" };
var blogs = new Blog[]
{
dotnetBlog,
dotnetCoreBlog
};
foreach (var blog in blogs)
{
context.Blogs.Add(blog);
}
context.SaveChanges();
var posts = new Post[]
{
new Post{Id= 1,Title="Dotnet 4.7 Released",Blog = dotnetBlog,
Content = "Dotnet 4.7 Released Contents", PublishedDateTime =
DateTime.Now},
new Post{Id= 1,Title=".NET Core 1.1 Released",Blog=
dotnetCoreBlog,
Content = ".NET Core 1.1 Released Contents", PublishedDateTime
=
DateTime.Now},
new Post{Id= 1,Title="EF Core 1.1 Released",Blog=
dotnetCoreBlog,
Content = "EF Core 1.1 Released Contents", PublishedDateTime =
DateTime.Now}
};
foreach (var post in posts)
{
context.Posts.Add(post);
}
context.SaveChanges();
}

In Program.cs, initialize DbInitializer in Main() by creating the BlogContext using dependency injection and pass the same to the DbInitializer.Initialize():

    public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<BlogContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred initializing
the database.");
}
}
host.Run();
}

One last piece of the puzzle is missing; we need to add migration whenever we add/manipulate data models, without which EF doesn't know how the database needs to be created/updated. The migration can be performed with the NuGet Package Manager console:

    Add-Migration InitialMigration

The preceding statement allows EF to create a migration file with tables created from the models configured in the DbContext. This can be done as follows:

    Update-Database

The preceding statement applies the migration created to the database. At this moment we are almost done with the EF configuration. We should run the application and verify the database regarding whether or not the proper schema and seed data were updated.

We could verify the table whether it contains seeded data using the following SQL Server Object Explorer:

Database created successfully

We can see that the schema was created properly inside the MSSQLLocalDB instance, and we should expand the tables and verify whether the seed data was updated or not. The seed data of the Blog entity was updated properly, which was verified with the following screenshot:

Blog table created with configured schema and seed data

The seed data of the Post entity was updated properly, which was verified with the following screenshot.

Post table created with configured schema and seed data

We have ensured that the database was created with the proper schema and seed data, and now we should start consuming the entities. In the next section, let's see how we can consume the entities in MVC using scaffolding rather than building everything on our own.

主站蜘蛛池模板: 苗栗市| 蒲江县| 彭山县| 崇阳县| 密云县| 讷河市| 兴文县| 三都| 额尔古纳市| 雷山县| 中宁县| 普兰店市| 会昌县| 余江县| 乳山市| 卫辉市| 大同县| 宜阳县| 桦甸市| 临漳县| 永兴县| 西乌珠穆沁旗| 青田县| 宣城市| 马边| 宝兴县| 浠水县| 怀远县| 承德市| 赤水市| 邵阳县| 白朗县| 南澳县| 临西县| 西林县| 娱乐| 淮阳县| 巧家县| 海伦市| 安丘市| 新建县|