Establishing a connection

To open a session to the database and query and update instances of your entities, you need to use DbContext, which is based on a combination of the unit of work and repository patterns.

Let's learn how to prepare the Tic-Tac-Toe application so that we can use Entity Framework Core 3 from scratch to connect to a SQL database via DbContext and a connection string:

  1. Go to the Solution Explorer and add a new folder called Data, add a new class called GameDbContext, and implement a DbSet property for each model (UserModel, TurnModel, and so on):
        public class GameDbContext : DbContext
{
public DbSet<GameInvitationModel> GameInvitationModels
{get; set; }
public DbSet<GameSessionModel> GameSessionModels { get;
set; }
public DbSet<TurnModel> TurnModels { get; set; }
public DbSet<UserModel> UserModels { get; set; }
public GameDbContext(DbContextOptions<GameDbContext>
dbContextOptions) : base(dbContextOptions) { }
}
  1. Register GameDbContext in the Startup class. Then, pass the connection string and database provider as parameters within the constructor. Currently, we only need a single instance, so we will use AddSingleton:
        var connectionString = 
_configuration.GetConnectionString("DefaultConnection"); services.AddEntityFrameworkSqlServer() .AddDbContext<GameDbContext>((serviceProvider,
options) => options.UseSqlServer(connectionString).
UseInternalServiceProvider(serviceProvider) ); var dbContextOptionsbuilder =
new DbContextOptionsBuilder<GameDbContext>() .UseSqlServer(connectionString); services.AddSingleton(dbContextOptionsbuilder.Options);
Please note that you will need to add the following using statements for the code to compile: using TicTacToe.Data; and
using Microsoft.EntityFrameworkCore;.

  1. Update the user service class called UserService.cs so that you can work with the game database context: GameDbContext.cs. Add a new public constructor and a private member for the game database context:
        private DbContextOptions<GameDbContext> _dbContextOptions; 
        public UserService(DbContextOptions<GameDbContext> 
dbContextOptions) { _dbContextOptions = dbContextOptions; }
  1. Update the RegisterUser method in UserService so that you can use the game database context: GameDbContext:
        public async Task<bool> RegisterUser(UserModel userModel) 
        { 
          using(var Database = new GameDbContext
(_dbContextOptions)) { Database.UserModels.Add(userModel); await Database.SaveChangesAsync(); return true; } }
  1. Add a new extension called ModelBuilderExtensions to the Extensions folder. This will be used to define table name conventions:
        public static class ModelBuilderExtensions 
        { 
          public static void RemovePluralizingTableNameConvention(
this ModelBuilder modelBuilder) { foreach (IMutableEntityType entity in
modelBuilder.Model.GetEntityTypes()) { entity.SetTableName(entity.DisplayName()); } } }

  1. Update the OnModelCreating method in the game database context, GameDbContext, to configure the models to configure the models that were discovered from the entity types exposed in DbSet properties, for example: public DbSet<UserModel> UserModels { get; set; }. Then, we call the ModelBuilderExtensions extension class to apply the table name conventions:
        protected override void OnModelCreating(ModelBuilder   
modelBuilder) { modelBuilder.RemovePluralizingTableNameConvention(); }
Note that we could also use another method called OnConfiguring in the database context in order to configure the database context without using DbContextOptions.
  1. Add a new class called GameDbContextFactory to the Data folder. This will be used to instantiate the game database context, GameDbContext, with specific options:
        public class GameDbContextFactory : 
IDesignTimeDbContextFactory<GameDbContext> { public GameDbContext CreateDbContext(string[] args) { var optionsBuilder = new
DbContextOptionsBuilder<GameDbContext>(); optionsBuilder.UseSqlServer(@"Server=
(localdb)MSSQLLocalDB;Database=TicTacToe;
Trusted_Connection=True;
MultipleActiveResultSets=true"); return new GameDbContext(optionsBuilder.Options); } }
Note that you will have to add the following using statements so that the code compiles: using Microsoft.EntityFrameworkCore; and using Microsoft.EntityFrameworkCore.Design;.

If you have worked with databases before, you should be familiar with the concept of connection strings. They contain the configuration (address, username, password, and more) and settings (encryption, protocol, and more) that are required so that we can connect to a database.

In ASP.NET Core 3, you can also use an appSettings.<env>.json file to configure connection strings. Connection strings are loaded automatically when we use the ConnectionStrings section within this file:

    "ConnectionStrings": {
"DefaultConnection":
"Server=(localdb)\MSSQLLocalDB;Database=TicTacToe;
Trusted_Connection=True;MultipleActiveResultSets=true"
},

As you can see, you can use the GetConnectionString method to retrieve a connection string at runtime:

    var databaseConnectionString =
_configuration.GetConnectionString("DefaultConnection");

This is everything you need to know in order to use the game database context, GameDbContext, and the corresponding default connection string stored within the appsettings.json configuration file of the Tic-Tac-Toe application.

Before we start using the game database context on our models, it is important to make sure that we have grasped all the required basics so that we can use our game database context to create and access database tables. It is recommended that every database table has a primary key if it is to qualify as a relational table; it needs to have a foreign key if it is related to another table. In the next section, we will look at how we are going to define our primary and foreign keys in our code through Data Annotations. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.146.173