Click here to Skip to main content
16,004,529 members
Articles / Web Development / ASP.NET / ASP.NET Core

Simplifying Data Access in ASP.NET MVC WebAPI with Class Library and Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.88/5 (3 votes)
13 Jun 2024CPOL2 min read 4.1K   6   4
Simplifying data access using class libraries and Entity Framework without the need for a .edmx file (ADO.NET)

Introduction

In modern web development, one of the key challenges is effectively managing data access while maintaining clean, modular code. ASP.NET MVC WebAPI provides a robust framework for building RESTful APIs, but integrating it with a data access layer can sometimes be complex. However, by leveraging class libraries and Entity Framework, we can streamline this process, making data access in our WebAPI projects efficient and maintainable.

In this article, we'll walk through the steps of setting up a class library for data access, integrating it with an ASP.NET MVC WebAPI project, and creating a simple API controller to fetch data from a database.

Setting up the DataAccessLayer Class Library

First, let's create a class library project named DataAccessLayer in our solution. Within this project, we'll define our data access logic using Entity Framework without the need for a .edmx file (ADO.NET).

  • DatabaseTransections Class

Within the DataAccessLayer project, we'll create a class named DatabaseTransections, inheriting from DbContext. This class will contain methods for fetching data from the database using Entity Framework. By encapsulating database interactions within this class, we promote code reusability and maintainability.

public class DatabaseTransections : DbContext
{
    public DatabaseTransections() : base("name=ConStr") { }
    public virtual DbSet<ProductEntity> Product { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProductEntity>().ToTable("tblProduct");
    }
}
  • ProductEntity and ProductRepository Classes

Next, we'll define our entity class, ProductEntity, to represent the data model for products in our database. Additionally, we'll create a ProductRepository class to handle CRUD operations for products, abstracting away the database-specific logic.

public class ProductEntity
{
    public int ID { get; set; }
    public int ProductCategory { get; set; }
    public string ProductName { get; set; }
    public int UnitPrice { get; set; }
    public int Quantity { get; set; }
}

public class ProductRepository
{
    private readonly DatabaseTransections transection;
    public ProductRepository(DatabaseTransections _transection) 
    { 
       transection = _transection; 
     }
     public List<ProductEntity> GetALLProducts(int? _productCategory)
     {
        try
        {
            return transection.Product.Where(m => m.ProductCategory == _productCategory).ToList();
         }
         catch (Exception ex)
         {
            return null;
         }
     }
}

Integrating with the WebAPI Project

Now, let's create an ASP.NET MVC WebAPI project named APILearning in our solution. We'll add a WebAPI controller named ProductController to expose endpoints for fetching product data. We'll add DataAccessLayer solution reference to access ProductRepository Class in WebAPI controller.

  • ProductController

Implement controller actions (methods) that map to HTTP verbs (GET, POST, PUT, DELETE) to handle API requests. These actions will interact with the ProductRepository to perform CRUD (Create, Read, Update, Delete) operations on product data.

public class ProductController : ApiController
{
    // GET api/product
    public IEnumerable<ProductEntity> Get()
    {
        return new ProductRepository(new DatabaseTransections()).GetALLProducts(null);
    }
  //Implement POST, PUT, DELETE methods by using ProductRepository
}

Benefits of This Approach

  • Separation of Concerns: The data access logic is encapsulated within the DataAccessLayer class library, promoting maintainability and reusability.
  • Testability: The use of dependency injection allows for easier unit testing of both the controller and the repository.
  • Flexibility: The data access layer can be easily extended to support additional entities and data operations.

Conclusion

By organizing our project into separate class libraries for data access and API logic, we promote separation of concerns and maintainability. Leveraging Entity Framework simplifies database interactions, allowing us to focus on building robust APIs without worrying about low-level database operations.

In summary, by following the steps outlined in this article, developers can streamline data access in ASP.NET MVC WebAPI projects, making them more scalable and maintainable in the long run.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Pakistan Pakistan
Results-driven Software Developer with 9 years of experience delivering innovative solutions. Managed, Developed and scaled numerous software applications from idea to finished product and beyond. A collaborative team player, adept at working closely with cross-functional teams to achieve project objectives. Demonstrated capability as a self-starter, consistently taking initiative and driving projects forward. Expertise in mission critical systems, agile methodologies, and creating robust software architectures. Committed to driving technological advancements and exceeding client expectations. Passionate about leveraging cutting-edge technologies to solve complex problems and deliver impactful software solutions.

Comments and Discussions

 
Questionsource code? Pin
msyoung26-Jun-24 10:06
msyoung26-Jun-24 10:06 
AnswerRe: source code? Pin
Zohaib Waqar7-Jul-24 22:25
Zohaib Waqar7-Jul-24 22:25 
I apologize, but the source code itself isn't directly attached to the article. However, I did make sure to include every step mentioned in the article itself.

Is there a specific part you'd like me to clarify?
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA24-Jun-24 6:08
professionalȘtefan-Mihai MOGA24-Jun-24 6:08 
GeneralRe: My vote of 5 Pin
Zohaib Waqar24-Jun-24 18:22
Zohaib Waqar24-Jun-24 18:22 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.