How To Configure Entity Framework Project with ASP.NET Core Web API Application

In this post, we will discuss, how to configure entity framework project with ASP.NET Core web API application.

Our exploration of Entity Framework core has taken us so far in this series. Integration with Entity Framework can be easily accomplished with ASP.NET Core API applications.  

My previous blog will be continued here.

ASP.NET Core Web API App Creation:

Select Add->New Project from the right-click menu of the Solution

The second step is to choose the ASP.NET Core template in the wizard.

Configure Entity Framework Project with ASP.NET Core Web API

Providing the name of the project is the third step.

Save the API Project template after selecting the template.

Configure Entity Framework Project with ASP.NET Core Web API

The project already defines the JSON format for the weather forecast API output, which you can see when running the application.

Configure Entity Framework Project with ASP.NET Core Web API

Note: Create an API startup project.

User Controllers should be added to the project as follows:

You need to add references to the AspWebAppCore project to the Domain and Data projects.

Configure Entity Framework Project with ASP.NET Core Web API

The second step is to build the solution

In order to build the solution, it’s really important to add the references

In step 3, you will have to add a new controller

Select Add-> Controller from the right-click menu of the controller folder. Using the Entity Framework template, select API Controller with actions.  

Once you click on Add, the scaffolding happens (Model class and Data context class). During scaffolding, all packages will be installed.

UserController is a class that contains API actions predefined by the API.

Modify the Package

The list of EF packages added during scaffolding can be observed in the project file.

EFCore will use the SqlServer provider, so the SqlLite package was replaced with SqlServer.

UsersController.cs

[HttpGet]
        public async Task<ActionResult<IEnumerable<User>>> GetUsers()
        {
            return await _context.Users.ToListAsync();
        }

Users are retrieved using the GetUsers() action.

  // GET: api/Users/5
        [HttpGet("{id}")]
        public async Task<ActionResult<User>> GetUser(int id)
        {
            var user = await _context.Users.FindAsync(id);

            if (user == null)
            {
                return NotFound();
            }

            return user;
        }

A user can be retrieved using the GetUser() action based on their UserId Key using the GetUser() action.

[HttpPut("{id}")]
        public async Task<IActionResult> PutUser(int id, User user)
        {
            if (id != user.Id)
            {
                return BadRequest();
            }

            _context.Entry(user).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

It is possible to update the user by using the PutUser() action.

[HttpPost]
        public async Task<ActionResult<User>> PostUser(User user)
        {
            _context.Users.Add(user);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetUser", new { id = user.Id }, user);
        }

A new user can be created with the PostUser() action.

[HttpDelete("{id}")]
        public async Task<ActionResult<User>> DeleteUser(int id)
        {
            var user = await _context.Users.FindAsync(id);
            if (user == null)
            {
                return NotFound();
            }

            _context.Users.Remove(user);
            await _context.SaveChangesAsync();

            return user;
        }

To delete a user, use the DeleteUser() action.

  private bool UserExists(int id)
        {
            return _context.Users.Any(e => e.Id == id);
        }

The user existence is checked with the UserExists() action.

Configure ASP.NET Core App with DbContext:

UseSqlServer() should be added to startup Configure() as part of services.DbContex

In the ConfigureService() method of Startup.cs, enter the following code.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<AppDBContext>(option => option
            .UseSqlServer(Configuration.GetConnectionString("AppConnection"))
            .EnableSensitiveDataLogging());
        }

Dependency injection is the default method for interacting with another feature in ASP.NET. Logging will be configured by default as well as managed by ASP.NET Core services.

Use Microsoft.EntityFrameworkCore to add the namespace.

In appsettings.json, specify the SQL connection string

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  },
  "ConnectionStrings": {
    "AppConnection": "Data Source=DESKTOP-585QGBN;Initial Catalog =EFCoreDemoDB; Integrated Security=SSPI"
  },
  "AllowedHosts": "*"
}

EF Core’s default logging settings allowed us to add a new detail to the SQL command log created by the above code.

Adding Constructor for DB Context

Here are the steps to add the code to AppDBContext.cs from the Data project.

 public AppDBContext(DbContextOptions<AppDBContext> options):base(options)
        {
            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
        }

Why do we need to add a constructor in AppDBContext.cs?

It is important to construct the AppDbContext before the controller due to the fact that the controller uses an AppDbContext instance that is passed to its constructor. ASP.NET Core will create the AppDBContext whenever the controller needs it, which is why we configured it in the Startup file.

With every HTTP call, a new controller and AppDbContext are initiated, so context tracking isn’t really necessary due to our application’s behavior as a disconnected client. Performance will be improved by disabling this feature.

AppDBContext.cs should remove OnConfiguring() and loggerFactory

Call the User API by running the application

AppDbContext returns the List of users as expected via the API/Users API.

While fetching the Users details, EF Core generates the following SQL command.

Conclusion:

By following the key steps discussed below, this blog post will assist you in understanding how to integrate Entity Framework core with your ASP application.NET Core web application project.

  • DbContext integration with ASP.NET Core web application
  • Understanding Dependency Injection and adding a constructor to DbContext.
  • The context tracking can be disabled to improve performance.

Leave a Comment