WPF Course, Creating a CRUD Application using Entity Framework and WPF

Windows Presentation Foundation (WPF) is a UI framework provided by Microsoft that is used for developing desktop applications. WPF offers powerful tools for composing user interfaces (UI) and facilitates integration with various data bindings and relational data stores. This course provides a detailed explanation of how to implement CRUD (Create, Read, Update, Delete) operations in WPF applications using Entity Framework.

1. Introduction to WPF and Entity Framework

WPF provides the ability to design UIs using XAML (Extensible Application Markup Language). With features like data binding, styling, and animation, it’s easy to create complex user interfaces. On the other hand, Entity Framework is an ORM (Object-Relational Mapping) framework that allows mapping relational database data to objects, making data manipulation easy. By combining WPF and Entity Framework, it’s straightforward to develop data-centric applications.

2. Setting Up the Development Environment

In this course, we will use Visual Studio 2022 to develop the WPF application. Additionally, we will interact with the database using Entity Framework Core. Below are the steps to set up the development environment.

  • Download and install Visual Studio 2022.
  • Create a new project and select the WPF App (.NET Core) template.
  • Install the NuGet packages required for development. Here, we will install Entity Framework Core and the corresponding database provider (e.g., Microsoft.EntityFrameworkCore.SqlServer).
  • Set the database connection string in the app settings file of the project (appsettings.json).

3. Defining the Data Model

The most important part of a CRUD application is the data model. With Entity Framework, C# classes can be used as data models. Below is how to define a “Product” model to be used as an example.


public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

The above Product class represents the product’s ID, name, and price. Now, we will create a DbContext class to sync this model with the database.


using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public DbSet Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionStringHere");
    }
}

4. Migration and Database Creation

After defining the data model, it’s necessary to create and update the database. This is done through the migration feature of Entity Framework. Run the following commands in the terminal or Package Manager Console to create the initial migration.

Add-Migration InitialCreate
Update-Database

By executing the above commands in order, the database will be created, and a table for the defined Product model will be generated.

5. Building the WPF UI

Now, let’s build the actual WPF user interface. In the XAML file, we will add buttons for data operations and a DataGrid for displaying data.



    
        
            
                
                
                
            
        
        
        
        
    


6. ViewModel and Data Binding

The MVVM (Model-View-ViewModel) pattern is widely used in WPF applications. By using the ViewModel, data can be bound between the model and the view. Below is how to define the ViewModel.


using System.Collections.ObjectModel;

public class ProductViewModel
{
    public ObservableCollection Products { get; set; }

    public ProductViewModel()
    {
        using (var context = new AppDbContext())
        {
            Products = new ObservableCollection(context.Products.ToList());
        }
    }

    public void AddProduct(Product product)
    {
        using (var context = new AppDbContext())
        {
            context.Products.Add(product);
            context.SaveChanges();
        }
    }

    public void EditProduct(Product product)
    {
        using (var context = new AppDbContext())
        {
            context.Products.Update(product);
            context.SaveChanges();
        }
    }

    public void DeleteProduct(int productId)
    {
        using (var context = new AppDbContext())
        {
            var product = context.Products.Find(productId);
            if (product != null)
            {
                context.Products.Remove(product);
                context.SaveChanges();
            }
        }
    }
}

7. Implementing CRUD Operations

Now we are ready to connect the UI to the ViewModel and implement CRUD operations. The CRUD methods will be called in the button click events. Below is how to implement the button click events.


private ProductViewModel viewModel;

public MainWindow()
{
    InitializeComponent();
    viewModel = new ProductViewModel();
    DataContext = viewModel;
}

private void AddButton_Click(object sender, RoutedEventArgs e)
{
    var newProduct = new Product
    {
        Name = "New Product",
        Price = 9.99m
    };
    viewModel.AddProduct(newProduct);
}

private void EditButton_Click(object sender, RoutedEventArgs e)
{
    // Edit logic
}

private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
    // Delete logic
}

8. Optimization and Conclusion

After completing the CRUD application, you may consider additional tasks such as error handling and validation to optimize the code and enhance reliability. Creating a new DbContext instance every time you access the database may affect performance, so it may be worth considering dependency injection through IoC (Inversion of Control).

We have looked at the process of creating a CRUD application using WPF and Entity Framework. The content described in this course is just a simple example, and actual applications may require more advanced features and architecture considerations.

9. Conclusion

The technologies using WPF and Entity Framework are powerful and provide a highly useful combination for creating applications that handle various data. It is hoped that this course has helped you understand the fundamental structure of a CRUD application and learn how to practically utilize WPF and Entity Framework.

Moving forward, there are many applications possible to enhance user experience by processing complex business logic or constructing diverse user interfaces.