How to use EF Core query types in ASP.NET Core 7

Entity Framework Main (EF Main for quick) is a preferred ORM (item-relational mapper) from Microsoft that allow for you to carry out CRUD functions (produce, go through, update, and delete) without the need of acquiring to know how the data is persisted in the fundamental database.

When doing the job with ORMs, we frequently leverage types that are mapped to databases tables. Nonetheless, what if we have a model that doesn’t mimic a databases table? How can we map non-entity styles and populate objects of this kind of a design in our purposes? We can attain this with query varieties.

In the beginning launched in EF Core 2.1, query varieties are non-entity kinds (courses) that can map to tables or sights in the databases with no an id column specified, that means tables and views that lack a critical. EF Main question styles make it easier to question views and model styles that really don’t demand identification columns. However, for the reason that question varieties really do not have an id column defined, you cannot insert, update, or delete facts making use of them. You can use them only to retrieve the facts.

Question forms enable you to specify a mapping among a database question and your domain courses. You can then use the identical question form with various styles of EF Core queries, these types of as LINQ to Entities or EF Core Migrations. 

This posting discusses how we can use EF Core query kinds in ASP.Net Main 7 programs. To work with the code illustrations offered in this posting, you ought to have Visual Studio 2022 Preview mounted in your system. If you don’t by now have a duplicate, you can download Visible Studio 2022 below.

Build an ASP.Web Core 7 Net API venture in Visible Studio 2022

1st off, let us create an ASP.Web Main Net API task in Visual Studio 2022. Next these ways will generate a new ASP.Net Core World wide web API challenge in Visible Studio 2022:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new job.”
  3. In the “Create new project” window, decide on “ASP.Web Core Website API” from the record of templates shown.
  4. Click Next.
  5. In the “Configure your new project” window, specify the identify and place for the new venture.
  6. Optionally examine the “Place remedy and challenge in the exact same directory” check box, based on your tastes.
  7. Click Subsequent.
  8. In the “Additional Information” window shown subsequent, under Framework, decide on .Net 7..
  9. Leave the check out box that states “Use controllers…” checked considering the fact that we’ll be making use of controllers in this case in point. Leave the “Authentication Type” set to “None” (default).
  10. Guarantee that the verify containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we won’t be applying any of all those features in this article.
  11. Click on Build.

We’ll use this ASP.Web Main 7 Internet API challenge to function with EF Main query kinds in the subsequent sections of this posting.

Performing with query types in ASP.Internet Main 7

Let’s start by building some entities that we can query. We’ll use the adhering to two courses, Teacher and Batch, in our instance.

    community course Instructor
        community int Id  get established 
        community string FirstName  get set 
        public string LastName  get set 
        public ICollection Batches  get established 
    community class Batch
        public int Id  get set 
        public string Title  get established 
        public int NoOfStudents  get set 
        general public int TeacherId  get set 

Generate a check out in your database

Now create a view named BatchDetails in your databases with the next code. We’ll use query styles to map to this view. 

Develop Watch BatchDetails AS
Pick t.FirstName, t.LastName, t.BatchTitle, t.NoOfStudents as Whole_College students
From Trainer t
Sign up for Batch b on b.Id = t.Id

We will also have to have a class that can be used to retail outlet the knowledge retrieved from the see we just designed. The pursuing code snippet illustrates how you can produce a class named BatchDetails to store the knowledge queried from the see.

general public course BatchDetails
        general public string FirstName  get set 
        community string LastName  get set 
        community string Title  get established 
        public int NoOfStudents  get established 

Configure the query variety in EF Main

You have two strategies to configure the question variety. If you want to refrain from cluttering your DbContext, you can produce your DbContext course as a partial course and then split the DbQuery declaration into a different file altogether.

Here is the written content of the DemoDbContext.cs file:

public partial course DemoDbContext : DbContext
        public DbSet Lecturers  get established 
        public DbSet Batches  get set 

And below is the information of the DemoDbContextQuery.cs file:

community partial class DemoDbContext : DbContext
        general public DbQuery Batches  get established 

You need to configure the query sort in the OnModelCreating system as demonstrated in the code snippet given beneath.

guarded override void OnModelCreating(ModelBuilder modelBuilder)


Build a repository in ASP.Internet Core

We’ll now make a repository to study information from the database. Be aware that, although the repository will interact with the database instantly, the controller will use the repository to get info. (We’ll implement the controller in the following part.) 

Create a file named IBatchRepository.cs with the adhering to code. IBatchRepository will serve as the interface for our BatchDetailsRepository.

community interface IBatchDetailsRepository
        community Record GetBatchDetails()

Build an additional file named BatchDetailsRepository.cs and enter the next code to make the repository course.

    general public class BatchDetailsRepository: IBatchDetailsRepository
        non-public DemoDbContext dbContext
        community BatchDetailsRepository(DemoDbContext demoDbContext)
            dbContext = demoDbContext
        general public List GetBatchDetails()
            return dbContext.BatchDetails.ToList()

Produce an API controller in ASP.Internet Core

Now, generate an API controller named BatchDetailsController in a file with the very same identify and a .cs extension. Then produce the adhering to code in there.

    public class BatchDetailsController : ControllerBase
        non-public IBatchDetailsRepository _batchDetailsRepository
        general public BatchDetailsController(IBatchDetailsRepository
            _batchDetailsRepository = batchDetailsRepository
        public IActionResult Get()
            return Alright(_batchDetailsRepository.GetBatchDetails())

Refer to the preceding code listing. Notice how dependency injection has been used to inject an occasion of sort IBatchDetailsRepository in the constructor of the BatchDetailsController class.

You can return question forms from raw SQL queries applying the FromSql system in the DbQuery form and they can participate in interactions as very well.

Lastly, there are two constraints of question sorts you should preserve in thoughts. As mentioned above, simply because query varieties can not be tracked by the context, you can only use them for reads, not writes. And you can’t use the Insert and Connect procedures of the DbContext when performing with question styles.

Copyright © 2022 IDG Communications, Inc.

You may also like