Click here to Skip to main content
14,575,959 members

Building an ASP.NET Core Web API application using Entity Developer

Rate this:
5.00 (1 vote)
Please Sign up or sign in to vote.
5.00 (1 vote)
2 Jun 2020CPOL
Building an ASP.NET Core Web API application using Entity Developer
Entity developer from Devart is an ORM tool that lets you design your data access layer visually - at the drop of a hat. This article presents a discussion on how we can work with Entity Developer to build a RESTful service in ASP.NET Core 3.1.

Introduction

Entity Developer from Devart is a very powerful modelling and code generation tool, an ORM tool to be more precise. Entity developer lets you design your data access layer visually - at the drop of a hat. Since the data access layer generated by Devart contains automated and generated code, chances of error are minimal.

The official website of Entity Developer states: "Entity Developer can help you design models for various .NET ORMs in one unified interface. You can get support for all ORMs in one tool, or you may purchase a separate edition, working with one of the supported ORMs."
Reference: https://www.devart.com/entitydeveloper/

Entity Developer supports ADO.NET Entity Framework, Entity Framework Core, Hibernate, LinqConnect, Telerik Data Access, and LINQ to SQL. It uses the Database-First approach and explains how to work with the ORM designer and code generation tool. This article presents a discussion on how we can work with Entity Developer to build a RESTful service in ASP.NET Core 3.1.

Pre-requisites

To be able to work with the code examples demonstrated in this article, you should have the following installed in your system:

  • Visual Studio 2019 Community Edition
  • SQL Server 2019 Developer Edition
  • Entity Developer

You can download .NET Core 3.1 from this link.

You can download Visual Studio 2019 from this link.

You can download SQL Server 2019 Developer Edition from this link.

You should also download and restore the AdventureWorks database, a Microsoft product sample for an online transaction processing (OLTP) in your system. You can download a copy of AdventureWorks database in your system from this link.

Create a New ASP.NET Core Web API Project in Visual Studio 2019

Assuming that the necessary software has been installed in your computer to be able to work with Entity Developer, follow the steps outlined below to create a new ASP.NET Core Web API project.

  1. First off, open the Visual Studio 2019 IDE
  2. Next, click "Create a new project" once the IDE has loaded
  3. Click "Create a new project"
  4. Next, select "ASP.NET Core Web Application"
  5. Click the "Next" button
  6. Specify the project name and location - where it should be stored in your system
  7. Optionally, click the "Place solution and project in the same directory" checkbox.
  8. Next, click the "Create" button
  9. In the "Create a new ASP.NET Core Web Application" dialog window that is shown next, select "API" as the project template.
  10. Select ASP.NET Core 3.1 or later as the version.
  11. You should disable the "Configure for HTTPS" and "Enable Docker Support" options by disabling the respective checkboxes.
  12. Since we'll not be using authentication in this example, specify authentication as "No Authentication".
  13. Finally, click on the "Create" button to finish the process.

Create an Entity Data Model using Entity Developer

In this section, we’ll explore how to create an Entity Data Model using Entity Developer. To create an Entity Data Model using Entity Developer in Visual Studio 2019, follow the steps outlined below:

  1. Right-click on the project in the Solution Explorer Window
  2. Select Add -> New Item

    Image 1

    Figure 1

    This would launch the "Entity Developer: Create Model Wizard" window as shown below:

    Image 2

    Figure 2

    Here's how you should specify how your model should be created. There are two options: Database First (this is selected by default) and Model First. In this example, we’ll take advantage of the Database First approach.

  3. Click on the "Next" button to continue.
  4. In the next screen, specify the connection properties and click on the “Next” button to continue.

    Image 3

    Figure 3

    In the next screen, you should specify what the model should contain. The "Generate from Database" option is selected by default as shown in the figure given below:

    Image 4

    Figure 4
  5. Since we’ll need the model to be created from the database, click on the “Next” button to continue.

    In the next screen, the database metadata is retrieved by the Entity Developer runtime and here's how the database objects are selected.

    Image 5

    Figure 5
  6. De-select all options and then specify only the database objects you would like to be a part of the model. For the sake of simplicity, let’s select the Person and EmailAddress tables only.

    Image 6

    Figure 6
  7. In the "Set up naming rules" screen, you can specify naming rules for your entities.

    Image 7

    Figure 7
  8. Since we'll not be making any change here, click on the "Next" button to continue.

    The screen that is shown next is "Model properties" as shown in the figure below:

    Image 8

    Figure 8
  9. Specify the Context Namespace as “AdventureWorksModel” and click on the “Next” button to continue. In the next screen, you can specify what your model diagram should contain.

    Image 9

    Figure 9

    Note that the two database objects we selected earlier is displayed and the “All Entities” radio button is selected by default.

  10. Since we'll not be changing anything here, click on the "Next" button to continue. In the next screen, you can choose the code generation templates if you want to.

    Image 10

    Figure 10
  11. Since we'll not be modifying anything here, click on the "Next" button to continue.

  12. In the next screen, click on the “Next” button to continue.

    Image 11

    Figure 11
  13. Click “Finish” to complete the process.

    Your ADO.NET Entity Data Model using Entity Developer has been created. Here’s how your Entity Data Model would look like:

    Image 12

    Figure 12

Create the API Controller

So far so good. Now that the Web API project and the Entity Data Model has been created, the next step is to create the API controller that would be used to interact with the Entity Data Model. To do this, follow the steps outlined below:

  1. Select the project in the Solution Explorer Window

    Image 13

    Figure 13
  2. Right-click and select Add->Controller

  3. In the “Add New Scaffold Item” window, select the “API controller with read/write actions” as the template

    Image 14

    Figure 14
  4. Click Add

  5. In the next screen, specify the name of the controller. Let’s name the controller as DefaultController.
  6. Click Add to create and add the controller to your project

We’ll use this controller to write action methods in the section that follows.

Reading Data via the Entity Data Model

In this section, we’ll examine how we can read data from the AdventureWorks database using the Entity Data Model we’ve created in the preceding section.

Create an interface named IAdvantureWorksRepository with the following code in it:

public interface IAdventureWorksRepository
{
    PersonDTO GetPerson(int personId);
}

Create a new class named PersonDTO with the following code in it:

public class PersonDTO
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
    }

Create a class named AdventureWorksRepository with the following content inside:

public class AdventureWorksRepository: IAdventureWorksRepository
    {
        public PersonDTO GetPersonById(int personId)
        {
            using(AdventureWorksModel dbContext = new
                  AdventureWorksModel())
            {
                var query = from p in dbContext.People join e in
                dbContext.EmailAddresses
                      on p.BusinessEntityID equals e.BusinessEntityID
                      where p.BusinessEntityID == personId
                            select new PersonDTO
                            {
                                FirstName= p.FirstName, 
                                LastName= p.LastName,
                                EmailAddress = e.EmailAddress1
                            };
                      return query.SingleOrDefault();
            }
        }
    }

The AdventureWorksRepository class extends the IAdventureWorksRepository interface and implements the GetPersonById method. The GetPersonById method returns an instance of PersonDTO.

The following code snippet shows how you can add the AdventureWorksRepository we've created as a scoped service in the ConfigureServices method of the Startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped(typeof(IAdventureWorksRepository),
    typeof(AdventureWorksRepository));
    services.AddControllers();
}

We can now take advantage of dependency injection in the controller as shown in the code snippet given below:

public class DefaultController : ControllerBase
{
   private readonly IAdventureWorksRepository _adventureWorksRepository;
   public DefaultController(IAdventureWorksRepository adventureWorksRepository)
   {
     _adventureWorksRepository = adventureWorksRepository;
   }
  //Action methods
}

The following code snippet shows how you can write an action method that accepts the business entity Id as a parameter and then calls the GetPersonById method of the AdventureWorksRepository.

[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
  var person = _adventureWorksRepository.GetPerson(id);
  return JsonConvert.SerializeObject(person);
}

The following code listing is the complete code of the DefaultController class for your reference.

[Route("api/[controller]")]
[ApiController]
public class DefaultController : ControllerBase
{
    private readonly IAdventureWorksRepository
                      _adventureWorksRepository;
    public DefaultController(IAdventureWorksRepository
                             adventureWorksRepository)
    {
        _adventureWorksRepository = adventureWorksRepository;
    }

    [HttpGet]
    public string Get()
    {
        return "Demonstrating Entity Developer";
    }

    [HttpGet("{id}", Name = "Get")]
    public string Get(int id)
    {
        var person = _adventureWorksRepository.GetPersonById(id);
        return JsonConvert.SerializeObject(person);
    }
}

When you execute the application and hit the Get(int id) endpoint, here’s how the output will be:

Image 15

Figure 15

Summary

Entity Developer from Devart helps you to become more productive as a developer - it includes support for working with ADO.NET Entity Framework, Entity Framework Core, Hibernate, LinqConnect, Telerik Data Access, and LINQ to SQL. Entity Developer is also built in Devart ADO.NET data providers - here's the link: https://www.devart.com/dotconnect/.

You can get started using Entity Developer after downloading a trial version from here: https://www.devart.com/entitydeveloper/download.html.

History

  • 2nd June, 2020: Initial version

License

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

Share

About the Author

Joydip Kanjilal
Architect
India India
Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.Net (2007 - 2012) for six consecutive years, as well as a speaker and the author of several books and articles. Here's the link to his MVP public profile: https://mvp.microsoft.com/en-us/PublicProfile/38659

He has around 25 years of experience in IT, with more than 18 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight and as Community Credit Winner several times.

Joydip has authored nine books, reviewed about a dozen books and written more than 500 articles for MSDN, CodeMagazine, InfoWorld, SSWUG, Simple-Talk, Visual Studio Magazine, TechBeacon, TechTarget and several other sites of repute. Many of his articles have been featured at Microsoft's Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

Joydip blogs regularly at https://www.infoworld.com/blog/microsoft-coder

Comments and Discussions

 
-- There are no messages in this forum --
Article
Posted 2 Jun 2020

Tagged as

Stats

2.9K views
5 bookmarked