May 6, 2024

excellentpix

Unlimited Technology

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

Entity Framework Core (EF Main for limited) is a well known ORM (object-relational mapper) from Microsoft that enable you to execute CRUD operations (create, go through, update, and delete) devoid of obtaining to know how the data is persisted in the underlying databases.

When doing the job with ORMs, we frequently leverage versions that are mapped to database tables. Even so, what if we have a product that does not mimic a databases desk? How can we map non-entity styles and populate objects of such a design in our purposes? We can complete this with question sorts.

Initially launched in EF Main 2.1, question kinds are non-entity kinds (classes) that can map to tables or sights in the databases devoid of an identity column specified, this means tables and views that lack a important. EF Main query varieties make it more simple to question views and model varieties that do not require identity columns. However, because query kinds do not have an identification column defined, you can not insert, update, or delete information utilizing them. You can use them only to retrieve the data.

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

This short article discusses how we can use EF Main question types in ASP.Net Main 7 programs. To perform with the code examples presented in this posting, you should really have Visible Studio 2022 Preview set up in your method. If you really don’t by now have a copy, you can obtain Visible Studio 2022 in this article.

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

Very first off, let us create an ASP.Net Main World-wide-web API job in Visible Studio 2022. Subsequent these methods will produce a new ASP.Internet Core Internet API task in Visual Studio 2022:

  1. Start the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, pick “ASP.Web Core Web API” from the list of templates shown.
  4. Click Subsequent.
  5. In the “Configure your new project” window, specify the name and site for the new project.
  6. Optionally check the “Place solution and project in the very same directory” check box, relying on your preferences.
  7. Simply click Following.
  8. In the “Additional Information” window revealed upcoming, beneath Framework, select .Net 7..
  9. Leave the look at box that states “Use controllers…” checked considering the fact that we’ll be applying controllers in this example. Go away the “Authentication Type” established to “None” (default).
  10. Make sure that the check packing containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we will not be employing any of those people capabilities in this article.
  11. Click Generate.

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

Doing work with question types in ASP.Web Main 7

Let us start off by developing some entities that we can question. We’ll use the following two lessons, Teacher and Batch, in our illustration.

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

Generate a see in your databases

Now create a look at named BatchDetails in your database with the next code. We’ll use query types to map to this perspective.

 
Generate Check out BatchDetails AS
Pick t.FirstName, t.LastName, t.BatchTitle, t.NoOfStudents as Full_Students
From Teacher t
Join Batch b on b.Id = t.Id

We will also require a class that can be applied to retail store the details retrieved from the watch we just developed. The adhering to code snippet illustrates how you can develop a course named BatchDetails to store the facts queried from the view.

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

Configure the query kind in EF Core

You have two strategies to configure the query form. If you want to chorus from cluttering your DbContext, you can produce your DbContext course as a partial class and then break up the DbQuery declaration into a different file completely.

Here is the content of the DemoDbContext.cs file:

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

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

 
general public partial course DemoDbContext : DbContext
    
        public DbQuery Batches  get set 
    

You should configure the question style in the OnModelCreating method as revealed in the code snippet given down below.

 
guarded override void OnModelCreating(ModelBuilder modelBuilder)

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

Make a repository in ASP.Net Core

We’ll now create a repository to examine info from the database. Observe that, even though the repository will interact with the database immediately, the controller will use the repository to get knowledge. (We’ll apply the controller in the next segment.)

Create a file named IBatchRepository.cs with the subsequent code. IBatchRepository will provide as the interface for our BatchDetailsRepository.

 
general public interface IBatchDetailsRepository
    
        public List GetBatchDetails()
    

Develop yet another file named BatchDetailsRepository.cs and enter the subsequent code to produce the repository course.

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

Make an API controller in ASP.Web Core

Now, create an API controller named BatchDetailsController in a file with the exact same identify and a .cs extension. Then generate the next code in there.

 
    [Route("api/[controller]")]
    [ApiController]
    general public course 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 utilized to inject an occasion of style IBatchDetailsRepository in the constructor of the BatchDetailsController class.

You can return query varieties from uncooked SQL queries employing the FromSql technique in the DbQuery form and they can take part in interactions as very well.

Lastly, there are two limits of query kinds you should keep in mind. As described above, mainly because query sorts are unable to be tracked by the context, you can only use them for reads, not writes. And you can not use the Include and Connect approaches of the DbContext when doing work with query forms.

Copyright © 2022 IDG Communications, Inc.