October 7, 2024

magellan-rfid

More Computer Please

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

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

Entity Framework Core (EF Core for shorter) is a well-liked ORM (item-relational mapper) from Microsoft that make it possible for you to carry out CRUD functions (develop, examine, update, and delete) devoid of owning to know how the information is persisted in the underlying database.

When functioning with ORMs, we typically leverage types that are mapped to database tables. However, what if we have a model that does not mimic a databases table? How can we map non-entity types and populate objects of this sort of a design in our applications? We can achieve this with question styles.

Originally launched in EF Core 2.1, question kinds are non-entity forms (lessons) that can map to tables or views in the database with out an identity column specified, this means tables and sights that lack a critical. EF Main query varieties make it less difficult to query views and product types that never have to have id columns. Having said that, simply because query sorts really do not have an id column described, you can not insert, update, or delete info utilizing them. You can use them only to retrieve the data.

Question types allow you to specify a mapping in between a database question and your domain classes. You can then use the same query type with different types of EF Main queries, these kinds of as LINQ to Entities or EF Main Migrations.

This short article discusses how we can use EF Core question types in ASP.Net Core 7 applications. To get the job done with the code examples presented in this short article, you should have Visible Studio 2022 Preview installed in your technique. If you really do not previously have a duplicate, you can obtain Visual Studio 2022 below.

Generate an ASP.Net Core 7 Website API project in Visible Studio 2022

Initially off, let us create an ASP.Internet Core Net API job in Visual Studio 2022. Adhering to these methods will develop a new ASP.Web Main World-wide-web API venture in Visible Studio 2022:

  1. Launch the Visual Studio 2022 IDE.
  2. Simply click on “Create new challenge.”
  3. In the “Create new project” window, decide on “ASP.Net Main Internet API” from the listing of templates shown.
  4. Click on Next.
  5. In the “Configure your new project” window, specify the name and locale for the new undertaking.
  6. Optionally verify the “Place alternative and challenge in the similar directory” look at box, dependent on your tastes.
  7. Click on Next.
  8. In the “Additional Information” window proven up coming, below Framework, find .Internet 7..
  9. Depart the examine box that suggests “Use controllers…” checked given that we’ll be utilizing controllers in this instance. Depart the “Authentication Type” established to “None” (default).
  10. Ensure that the check bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we will not be employing any of individuals functions right here.
  11. Click Build.

We’ll use this ASP.Net Core 7 World-wide-web API venture to function with EF Core question varieties in the subsequent sections of this write-up.

Functioning with query varieties in ASP.Web Core 7

Let’s start off by creating some entities that we can question. We’ll use the next two classes, Trainer and Batch, in our case in point.

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

Develop a see in your databases

Now create a see named BatchDetails in your database with the next code. We’ll use question forms to map to this perspective.

 
Build Watch BatchDetails AS
Decide on t.FirstName, t.LastName, t.BatchTitle, t.NoOfStudents as Complete_Pupils
From Teacher t
Be part of Batch b on b.Id = t.Id

We will also have to have a course that can be utilized to shop the facts retrieved from the see we just produced. The following code snippet illustrates how you can make a class named BatchDetails to store the info queried from the check out.

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

Configure the query variety in EF Main

You have two approaches to configure the question type. If you want to chorus from cluttering your DbContext, you can build your DbContext course as a partial course and then break up the DbQuery declaration into a different file altogether.

Listed here is the written content of the DemoDbContext.cs file:

 
general public partial class DemoDbContext : DbContext
    
        general public DbSet Instructors  get established 
        general public DbSet Batches  get established 
    

And below is the written content of the DemoDbContextQuery.cs file:

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

You should really configure the query type in the OnModelCreating process as proven in the code snippet presented below.

 
guarded override void OnModelCreating(ModelBuilder modelBuilder)

    modelBuilder.Question().ToView("BatchDetails")

Produce a repository in ASP.Internet Main

We’ll now generate a repository to browse knowledge from the databases. Be aware that, while the repository will interact with the database right, the controller will use the repository to get info. (We’ll implement the controller in the future section.)

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

 
public interface IBatchDetailsRepository
    
        general public Checklist GetBatchDetails()
    

Develop one more file named BatchDetailsRepository.cs and enter the pursuing code to make the repository class.

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

Build an API controller in ASP.Net Main

Now, generate an API controller named BatchDetailsController in a file with the exact title and a .cs extension. Then produce the following code in there.

 
    [Route("api/[controller]")]
    [ApiController]
    community class BatchDetailsController : ControllerBase
    
        personal IBatchDetailsRepository _batchDetailsRepository
        general public BatchDetailsController(IBatchDetailsRepository
        batchDetailsRepository)
        
            _batchDetailsRepository = batchDetailsRepository
        
        [HttpGet]
        public IActionResult Get()
        
            return Alright(_batchDetailsRepository.GetBatchDetails())
        
    

Refer to the preceding code listing. Take note how dependency injection has been applied to inject an occasion of type IBatchDetailsRepository in the constructor of the BatchDetailsController course.

You can return question sorts from uncooked SQL queries employing the FromSql system in the DbQuery style and they can participate in interactions as perfectly.

Eventually, there are two limitations of query forms you should really hold in mind. As mentioned earlier mentioned, since question types are not able to be tracked by the context, you can only use them for reads, not writes. And you are unable to use the Incorporate and Connect strategies of the DbContext when working with query varieties.

Copyright © 2022 IDG Communications, Inc.