Creating, reading, updating, and deleting data

So far, we have defined our models and got the database up and running in a consistent and coherent way. In this section, we will learn how to work with data and execute create, read, update, and delete operations.

Let's learn how to use GameDbContext to work with data:

  1. First, update UserService, remove ConcurrencyBag and the static constructor, and update the GetUserByEmail method:
        public async Task<UserModel> GetUserByEmail(string email) 
        { 
          using (var Database = new 
GameDbContext(_dbContextOptions)) { return await Database.UserModels.FirstOrDefaultAsync(
x => x.Email == email); } }
  1. Update the UpdateUser method in UserService to learn how to update data using the database context:
        public async Task UpdateUser(UserModel userModel) 
        { 
          using (var gameDbContext =
new GameDbContext(_dbContextOptions)) { gameDbContext.Update(userModel); await gameDbContext.SaveChangesAsync(); } }
  1. Update the GetTopUsers method within UserService to learn how to build advanced queries with sorting and filtered data using the database context:
        public async Task<IEnumerable<UserModel>> GetTopUsers(
int numberOfUsers) { using (var gameDbContext =
new GameDbContext(_dbContextOptions)) { return await gameDbContext.UserModels.OrderByDescending(
x => x.Score).ToListAsync(); } }

  1. Add a new method called IsUserExisting to UserService. This will be used to check whether a user exists. Update the IUserService interface:
        public async Task<bool> IsUserExisting(string email) 
        { 
          using (var gameDbContext =
new GameDbContext(_dbContextOptions)) { return await gameDbContext.UserModels.AnyAsync(
user => user.Email == email); } }

In this section, you've learned how to configure your applications so that they can use Entity Framework Core 3 and all of its useful and interesting features. This is a great way of abstracting complexity and removing time-consuming tasks from your daily life as a developer.

You don't need to learn about any additional languages (such as SQL), nor do you need to change environments to create, read, update, and delete records in a database. Everything can be done from within your code and from within Visual Studio to ensure high developer productivity and efficiency.

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

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