Entity Framework in WPF(Windows Presentation Foundation)App

Entity Framework in WPFWindows Presentation FoundationApp

In this post, we shall learn how to use Entity Framework in WPF(Windows Presentation Foundation)App.

In this article, we shall see the basic usage of EFCore DBContext object both EFCore without Dependency injection and with Dependency injection.

We shall scaffold the existing database.

Then leverage Generic HostBuilder to register the DBContext objects in the IoC container and then use it to perform CRUD operation on the database.

We will also see how the DBContext object can be accessed directly in the application.

Today in this article, we will cover below aspects,

We already looked at how to Use a Generic Host Builder for Dependency Injection in .NET Core Windows Presentation Foundation applications.

Let’s look into how to use Generic HostBuilder to create DI Container and inject the required dependency within the WPF app .NET Core application.

Getting started

Here I am using the .NET Core WPF application,

Entity Framework in WPFWindows Presentation FoundationApp

Let’s create a generic HosBuilder and register the dependencies that need to be injected which is explained in detail below.

Create a DI Container and Initialize the Host

We shall try attempting to use Generic HostBuilder for non-host WPF applications today.

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

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

The HostBuilder class is available from the following namespace,

using Microsoft.Extensions.Hosting;

In the WPF application, we shall use App.xaml as an entry point to set up the IoC container.

Here below is the complete implementation of our IoC Container.

Entity Framework in WPFWindows Presentation FoundationApp

For more details, please here for the complete code base.

Creating DBContext scaffolding using EFCore Tools

To enable EntityFrameworkCore in the application, we need

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

PM> Install-Package Microsoft.EntityFrameworkCore.Tools

Additionally, please install below NuGet packages,

PM> Install-Package Microsoft.EntityFrameworkCore -Version 3.1.3
PM>Install-Package Microsoft.EntityFrameworkCore.Design -Version 3.1.3
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.1.3

We are all set with the setup, let’s now start using an existing database and scaffold it using EFCore

Database First – Scaffolding for Existing Database

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

Entity Framework in WPFWindows Presentation FoundationApp

Use the below commands to scaffold the database as below,

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

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.

Let register the generated DBContext in the container,

host = new HostBuilder()
           .ConfigureServices((hostContext, services) =>
           {
               //Add business services as needed
               services.AddScoped<IEmployeeViewModel, EmployeeViewModel>();
               services.AddDbContext<EmployeeContext>(options =>
               {
                   options.UseSqlServer("Server=localhost\\SQL;Database=master;Trusted_Connection=True;");
               });

               //Lets Create single tone instance of Master windows
               services.AddSingleton<EmployeeWindow>();

           }).Build();

DBContext in ViewModel Class

Generated DBContext can be initialized within the Data Access Layer or any other layer using Constructor injections.

Here in the example, i am initializing it in the ViewModel class.

Entity Framework in WPFWindows Presentation FoundationApp

Here is the complete implementation,

 public partial class EmployeeWindow : Window
    {

        private readonly IEmployeeViewModel _businessObject;
        public EmployeeWindow(IEmployeeViewModel business)
        {
            InitializeComponent();
            _businessObject = business;

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            List<string> str = _businessObject.GetEmployeeDetails();
            MessageBox.Show($"Employee Numbers are {{{string.Join(", ", str)}}}");

        }
    }

On a similar line, you can add other CRUD methods as required,

Entity Framework in WPFWindows Presentation FoundationApp

Here is a complete implementation of ViewModel class,

Entity Framework in WPFWindows Presentation FoundationApp

Using DBContext without Dependency Injection

If you would like to use DBContext without DI , please use the logic as below.

Above IoC usage of DBContext takes care of creating DBContext as and when needed.

Framework-based IoC containers also dispose of those objects when their usage is done.

When not using IoC, you shall be responsible for managing the lifetime of the DBContext object including disposing of it after every usage.

The below example demonstrates how to create DBContext using the ‘using statement.

 public List<string> GetEmployeeDetails()
        {

            var empList = new List<string>();

            using (var context = new EmployeeContext())
            {
                empList = context.Employee.AsEnumerable().Select(x => x.EmployeeId).ToList();
            }

            return empList;
        }

That’s all! Happy coding.

Summary

In this post, we learned how to use Entity Framework Core in a Windows Presentation Foundation application. We learned to scaffold the existing database and then leverage Generic HostBuilder to register the DBContext objects in the IoC container for WPF.



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.



Leave a Reply

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