• No results found

Creating a DbSeeder class

Let's start with adding a DbSeeder.cs class in the /Data/ folder. This class will be using the ApplicationDbContext to create sample data, so we'll have to find a way to have it available there without creating an additional instance. We can do that using the ASP.NET Core DI pattern in the following way:

using Microsoft.EntityFrameworkCore;

private ApplicationDbContext DbContext;

#endregion Private Members #region Constructor

public DbSeeder(ApplicationDbContext dbContext) {

DbContext = dbContext;

}

#endregion Constructor #region Public Methods

public async Task SeedAsync() {

// Create the Db if it doesn't exist DbContext.Database.EnsureCreated();

// Create default Users

if (await DbContext.Users.CountAsync() == 0) CreateUsers();

// Create default Items (if there are none) and Comments if (await DbContext.Items.CountAsync() == 0) CreateItems();

}

#endregion Public Methods #region Seed Methods private void CreateUsers() {

// local variables

DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00);

DateTime lastModifiedDate = DateTime.Now;

// Create the "Admin" ApplicationUser account (if it doesn't exist already)

var user_Admin = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Admin", Email =

"[email protected]", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; Guid.NewGuid().ToString(), UserName = "Ryan", Email =

"[email protected]", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate };

var user_Solice = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Solice", Email =

"[email protected]", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate };

var user_Vodan = new ApplicationUser() { Id = Guid.NewGuid().ToString(), UserName = "Vodan", Email =

"[email protected]", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate };

// Insert sample registered users into the Database

DbContext.Users.AddRange(user_Ryan, user_Solice, user_Vodan);

#endif

DbContext.SaveChanges();

}

private void CreateItems() {

DateTime(2015, 12, 31).AddDays(-num)));

}

#endif

EntityEntry<Item> e1 = DbContext.Items.Add(new Item() { you play against a computer opponent or another human being.

The game features a well-developed AI, an intuitive and clear interface and an enticing level of gameplay.",

Notes = "This is a sample record created by the Code-First

EntityEntry<Item> e2 = DbContext.Items.Add(new Item() {

UserId = authorId, Title = "Minetest",

Description = "Open-Source alternative to Minecraft",

Text = @"The Minetest gameplay is very similar to Minecraft's:

you are playing in a 3D open world, where you can create and/or remove various types of blocks.

Minetest feature both single-player and multi-player game modes.

It also has support for custom mods, additional texture packs and other custom/personalization options.

Minetest has been released in 2015 under GNU Lesser

EntityEntry<Item> e3 = DbContext.Items.Add(new Item() {

UserId = authorId,

Title = "Relic Hunters Zero",

Description = "A free game about shooting evil space ducks with tiny, cute guns.",

Text = @"Relic Hunters Zero is fast, tactical and also very smooth to play.

It also enables the users to look at the source code, so they can can get creative and keep this game alive, fun and free for years to come.

EntityEntry<Item> e4 = DbContext.Items.Add(new Item() {

UserId = authorId, Title = "SuperTux",

Description = "A classic 2D jump and run, side-scrolling game similar to the Super Mario series.",

Text = @"The game is currently under Milestone 3. The Milestone 2, which is currently out, features the following:

- a nearly completely rewritten game engine based Island and the development levels in Incubator Island

- a final boss in Icy Island

EntityEntry<Item> e5 = DbContext.Items.Add(new Item() {

Other than playing left to right or top to bottom, you'll be able to place your tiles above or beyond other tiles.

Since the game features more fields, it also uses a larger letter set.

You can either play against the computer, players from your LAN or from the Internet.

The game also features a set of game servers where you can challenge players from all over the world and get ranked into an official, ELO-based rating/ladder system.

/// <param name="userId">the author ID</param>

/// <param name="id">the item ID</param>

/// <param name="createdDate">the item CreatedDate</param>

/// <returns></returns>

private Item GetSampleItem(int id, string authorId, int viewCount, DateTime createdDate) item {0}: Lorem ipsum dolor sit amet.", id),

Notes = "This is a sample record created by the Code-First

/// Generate a sample array of Comments (for testing purposes only).

/// </summary>

/// <param name="n"></param>

/// <param name="item"></param>

/// <param name="authorID"></param>

/// <returns></returns>

private Comment GetSampleComment(int n, int itemId, string authorId, DateTime createdDate)

#endregion Utility Methods }

That's an impressive amount of code, yet there's nothing to worry about since it's full of repeating tasks. To properly understand what we're doing here let's split it into six parts, each one corresponding to a #region section we defined within the source code:

The Private Members, where we define the DbContext object that we'll be using a lot in the methods in the following sections.

The Constructor region, containing the aforementioned DbContext using DI.

The Seed region, containing the only public method of this class: SeedAsync, which is in charge of the seeding task by making use of the other private methods defined in the following section.

The Create Entities region, containing a couple of methods that will create the Admin user (plus a set of sample users) plus a grand total of 105 generic Item entities.

The Utility Methods region, containing some internal functions used to create sample Item and Comment entities with bulk strategies.

Related documents