Using Entity Framework in Windows Form Desktop Application

Using Entity Framework in Windows Form Desktop Application

In this post, we shall learn how to use Entity Framework in Windows Form Desktop Application in the .NET Core.

We shall leverage Dependency injection (DI) in the Desktop Application and will try to use EFCore DBContext from the IoC container.

Today in this article, we will cover below aspects,

We shall also see consuming EFCore DBCOntext without using Dependency injection (DI).

We shall check the overall below steps,

We already looked at how to Use a Generic Host Builder for Dependency injection in .NET Core Windows form applications.

We shall extend the same concept for performing Database CRUD operations using Entity Framework.

Let’s look into how to create DI Container and inject the required dependencies like DBContext within the Windows form-based Desktop .NET Core application.

Getting started

Here I am using the .NET Core 3.1 Windows Form application,

Using Entity Framework in Windows Form Desktop Application

Configuring Entity Framework in Windows App

EFCore Package Manager Console Tool can be installed by using the below Nuget Package within the project directory,

PM> Install-Package Microsoft.EntityFrameworkCore -Version 3.1.0

Please install below additional Nuget packages in the application,

  • “Microsoft.EntityFrameworkCore”
  • “Microsoft.EntityFrameworkCore.Design”
  • “Microsoft.EntityFrameworkCore.SqlServer”

Configure Generic HostBuilder

The HostBuilder class is available from the following namespace,

using Microsoft.Extensions.Hosting;

Please install the NuGet package from the Nuget Package Manager or PMC,

PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.0

Creating EmployeeContext using EFCore Tools

Below is the database schema we shall be using for performing CRUD operations,

Entity Framework without dependency injection

EFCore Package Manager Console Tool can be installed by using the below NuGet package within the project directory,

PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.0

Use the below commands to scaffold the database as below,

PM> Scaffold-DbContext "Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer

Using Entity Framework in Windows Form Desktop Application

The above commands shall add all the required scaffolding including DbContext and model entities to the applications.

You can Create the scaffolding for one or multiple tables depending on the requirements.

Using the Dependency Injection – Approach 1

Let’s use the dependency injection approach create a DI Container and Initialize the Host with DBContext.

Please create Generic HosBuilder and register the dependencies that need to be injected. These changes can be implemented in the Main() method.

         ///Generate Host Builder and Register the Services for DI
            var builder = new HostBuilder()
               .ConfigureServices((hostContext, services) =>
               {
                   services.AddDbContext<EmployeeContext>(options =>
                     {
                         options.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=master;Trusted_Connection=True;");
                     });
               });

            var host = builder.Build();

Let’s use the required service and initialize our application with the Master Form as below,

 using (var serviceScope = host.Services.CreateScope())
            {
                var services = serviceScope.ServiceProvider;
                try
                {
                    var logg = services.GetRequiredService<ILogger<Form1>>();
                    var employeeContext = services.GetRequiredService<EmployeeContext>();
                    Application.Run(new Form1(employeeContext));

                    Console.WriteLine("Success");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error Occured");
                }
            }

In the above code below line lanches the forms app with EmployeeContext resolved from IoC service container.

Application.Run(new Form1(employeeContext));

EmployeeContext is generated using EntityFrameworkCore scaffolding tool which is discussed below.

Context class can be created for single or multiple tables as needed. Please read the article on Understanding Scaffold Commands in Entity Framework for more details.

We shall be consuming EmployeeContext within Form class but if you need EmployeeContext in other classes or module then you can easily do so, using Constructor injection in any class of your choice.

References: Accessing EF DBContext in Repository

Using DBContext in Form class

EmployeeContext can be initialized within the Master Form class using Constructor injections.

Using Entity Framework in Windows Form Desktop Application

Here below is the complete code,

  private void LoadEmployee_Click(object sender, EventArgs e)
        {
            try
            {
                // Perform Business Logic here 
                string[] employeeName = _employeeContext.Employee.AsEnumerable().Select(x => x.EmployeeId).ToArray();

                MessageBox.Show($"Employee Numbers are {{{string.Join(", ", employeeName)}}}");
            }
            catch (Exception ex)
            {
                //Log technical exception 
                MessageBox.Show(ex.Message);
                //Return exception repsponse here
                throw;

            }
        }

Using DBContext without Dependency Injection – Approach 2

If you do not want to use DI, it is pretty straightforward to use DBContext anywhere in the project.

EmployeeContext becomes accessible in your module by adding below the line of code.

Please add the required using references.

Using Entity Framework in Windows Form Desktop Application

Let’s launch the application and execute the Button click event by clicking the “Load Employee Data” function.

Finally, we are able to retrieve Employee Ids from the SQL database successfully.

Using Entity Framework in Windows Form Desktop Application

That’s All! Happy Coding!

I have extended the application to further bind the database to the Grid View Control in the below article.

If you need a code base for this article kindly visit the article on DI using Generic Host Builder in Windows Forms app

That’s all! Happy coding

Summary

In this post, we learned how to use Entity Framework Core in a desktop windows form application in the .NET Core. We also learned how within Windows form app how to scaffold the existing database and then leverage Generic HostBuilder to register the DBContext objects in the IoC container and perform basic CRUD operations.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



3 thoughts on “Using Entity Framework in Windows Form Desktop Application

  1. How do you deploy a WinForm application that uses EF Core ? Can you show the steps involved to deploy a WinForm application with EF Core ? Do you have to deploy the .mdf file if EF Core was used with Microsoft SQL Server. Maybe a video series on YouTube would be even better that shows all of this.

Leave a Reply

Your email address will not be published. Required fields are marked *