Search This Blog

Monday, September 22, 2025

Q36-Q40(EF)

Q36. What is the difference between Include and Join in entity framework?
Q37. What will be your approach in case you want to call a manual stored procedure from your dot net code with Entity Framework?
Q38: How to optimize entity framework queries if taking time?
Q39: What are the various approach in EF. Tell the difference between them. 
Q40. What is lazy loading in entity framework.?

=============================================================================
Q36. What is the difference between Include and Join in entity framework?

Answer:
Refer -> .NET Core Q21

=============================================================================
Q37. What will be your approach in case you want to call a manual stored procedure from your dot net code with Entity Framework?

Answer:
Refer -> .NET Core Q25
=============================================================================
Q38: How to optimize entity framework queries if taking time?

Answer:

1. Ensure proper indexes exist for frequently queried columns at database side. 
2. Review the execution plan of the generated SQL to catch table scans or bad joins.
3. Avoid fetching unnecessary data: Use Select to project only required columns instead of pulling full entities.
4. Use AsNoTracking() for read-only queries to skip change tracking overhead.
5. Be mindful with Include – only eager load what’s needed. Overusing it can explode query size.
6. Use IQueryable and filter the data at database side. database side filtering. 

Snip 1:
var productNames = context.Products
    .Where(p => p.IsActive)
    .Select(p => p.Name)
    .ToList();

=============================================================================
Q39: What are the various approach in EF. Tell the difference between them. 

Answer:
There are 3 approaches we can proceed with Database First, Model First and Code First. 

Database-First
  • You start with an existing database.
  • EF generates entity classes and a model (.edmx in EF6, or scaffolding in EF Core) from the schema.
  • Any changes in the database require updating the model from the database.
  • Useful when the DB already exists and is the source of truth.
Model-First
  • You start by designing your conceptual model (entities, relationships) visually in the EF Designer (.edmx).
  • EF generates both the database schema and entity classes from the model.
  • Changes to the model flow down to the database via generated DDL scripts.
  • Good for greenfield projects where you want to think in terms of domain entities first, not database tables
Code-First
  • You start by writing C# classes (POCOs – Plain Old CLR Objects).
  • EF builds the database schema based on these classes and configuration (attributes or Fluent API).
  • Database migrations (Add-Migration, Update-Database) help evolve the schema over time.
  • This is the preferred approach in EF Core and modern .NET because it avoids the designer .edmx and keeps everything in code.

=============================================================================




=============================================================================

Thursday, September 18, 2025

CleanArchitecture

 SchoolSystemSolution 

├──  <<projectname>>.Domain                 // Enterprise business rules.  Class Library project

│   ├── Entities

│   │   ├── Student.cs

│   │   ├── Teacher.cs

│   │   └── Admin.cs

│   └── ValueObjects (if needed)

├──  <<projectname>>.Application            // Application business rules. Class Library project

│   ├── DTOs

│   │   ├── StudentDto.cs

│   │   ├── TeacherDto.cs

│   │   └── AdminDto.cs

│   ├── Interfaces

│   │   ├── IStudentRepository.cs

│   │   ├── ITeacherRepository.cs

│   │   └── IAdminRepository.cs

│   ├── Services (or UseCases)

│   │   ├── StudentService.cs

│   │   ├── TeacherService.cs

│   │   └── AdminService.cs

│   └── Mapping (optional: AutoMapper profiles)

├──  <<projectname>>.Infrastructure      // External concerns (EF, Repositories, etc.)

│   ├── Data                                            //Class Library project

│   │   └──  <<projectname>>DbContext.cs

│   ├── Repositories

│   │   ├── StudentRepository.cs   // implements IStudentRepository

│   │   ├── TeacherRepository.cs

│   │   └── AdminRepository.cs

│   └── Migrations

└──  <<projectname>>.Api                    // Framework/UI layer. WebAPI project

    ├── Controllers

    │   ├── StudentController.cs

    │   ├── TeacherController.cs

    │   └── AdminController.cs

    ├── Program.cs

    ├── appsettings.json

    └── Startup.cs (if not using minimal APIs)


Wednesday, June 16, 2021

Q31-Q35

Q31. Difference between Middleware and filters in .net core mvc?
Q32. Life cycle of dotnet 8 MVC application?
Q33. When to use middleware and when to use filters in .net core?
Q34: What is CLEAN or Onion architecture design pattern?

=======================================================================Q31. Difference between Middleware and filters in .net core mvc?

Answer:
Middlewares
1) They are part of .net core and have access to httpcontext objects. they can be present even is project is not in mvc, api structure. 
2) Good in case you want to do changtes at httpcontet objects like authentication etc. 

Filters
1) They are present only in case of MVC and api. 
2) Good in case you want tocheck something around MVC contexts objects like post action filter

=======================================================================Q32. Life cycle of .net core MVC application?

Answer:
Life cycle of .net core application consists of two parts = 1st life cycle part specific to .net core + 2nd General life cycle part of MVC. 
  1. program.cs
  2. Authentication, Authorization etc middlewares
  3. Routing middleware will create routing map on hosted application server
  4. Controller 
  5. Action
  6. View
=======================================================================Q33. When to use middleware and when to use filters in .net core?

Answer:
Filters are something specific to MVC patterns that can be applied on top of our controllers. 
Filters and Middleware does the same functionality, but main difference lies in their scope. 

Middleware applies globally to all requests. eg : logging request and response, Handling exceptions globally, Managing CORS, Authentication/ Authorization. 

Filters applies specifically to a controller to an action of a controller. its mainly used to do validation of the model. 

=======================================================================






=======================================================================
Q34: What is CLEAN or Onion architecture design pattern?

Answer:
The Clean Architecture, often also referred to as Onion Architecture, is a software design pattern that aims to separate concerns and enforce dependency inversion, making systems more maintainable, testable, and adaptable to changes.
     
Key Concepts:
Clean Architecture is composed of layers arranged like an onion, where:
Core logic is at the center and Outer layers depend on inner layers, but not the other way around.



=======================================================================

Monday, June 14, 2021

Q26-Q30

Q26. What is the use of appsettings.json in .net core?
Q27. What are user secrets in .net core?
Q28. What is reverse proxy server .net core?
Q29. What is the use of launchSettings.json file in .net core?
Q30. What is the difference between  MapWhen and Map in dotnet 8?

==========================================================================================
Q26. What is the use of appsettings.json in .net core?

Answer:
1) Used to store configuration settings such as connection string, application level global variable, logging level configurations etc
2) We can store JWT key in appsettings.json file but it is NOT advisable. it can be saved here for temporary development phase. 
3) appSettings.json file could be environment specific as well. appsettings.<environment>.json

==========================================================================================
Q27. What are user secrets in .net core?

Answer:
If we do not want to share the secrets like API keys, connection string, connection information to cloud service (azure, aws) etc to anyone who can clone your project. 

For this .net core has given an option of user secret file which is outside the project tree structure. you can manage this file by right click the project and choose manage secrets option. 

Secret.json is the file which will be created to store secrets. 




==========================================================================================
Q28. What is reverse proxy server .net core?

Answer:
1) reverse proxy came into picture when we are using kestral server in .net core. 
2) Kestrel can be used by itself or with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. A reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.



==========================================================================================
Q29. What are the use of launchSettings.json file in .net core?

Answer:
launchSetting.json under property folder is mainly for local development. 
Hosted application url in local, Environment variables are part of launchSettings.json file. 


==========================================================================================
Q30. What is the difference between Map and MapWhen in dotnet 8?

Answer:
Both Map and MapWhen are used to branch middleware pipeline. 

Map: 
This method is used to branch the pipeline based on specific requested path. 

app.Map("/maptest", HandleMapTest);

MapWhen:
Enables branching pipeline. Runs specified middleware if condition is met.


    app.MapWhen(context => {
        return context.Request.Query.ContainsKey("somekey");
    }, HandleBranch);
==========================================================================================

Thursday, April 22, 2021

Q21-Q25

Q21. What is the difference between Include and Join in entity framework?
Q22. What is the strategy to migrate from .net framework to .net core?
Q23. What are the 3 parts of JWT?
Q24. How JWT works? How we get values of JWT token?
Q25. What will be your approach in case you want to call a manual stored procedure from your dot net code with Entity Framework?
------------------------------------------------------------------------------------------------------------------------------------------
Q21. What is the difference between Include and Join in entity framework?

Answer:
At times we get same results on using Include or Join but below are the differences. 

Include
1. It does the eager loading of underlying property for you. 
2. No filter on columns.
3. Include can only be used with actual inter related tables. They must have primary-foreign key relation between them. eg Product and Product details table. 
4. In example below it generates the left join between table product and productdetails behind the scenes. 

var products = context.Products
    .Include(p => p.ProductDetails)
    .ToList();

------------
Join
1. It does not do the eager loading. 
2. We can put filter on number of columns and columns we want. The advantage of Join is, if you dont need additional data you wont get it. 
3. Joins are flexible enough to query around tables which are not directly related like student and Collage over city to check all collages present in student city. 
4. For above product and productDetails below will be the query. Join gives more flexibility but bigger code. 

var productsWithDetails = from product in context.Products
                          join details in context.ProductDetails
                          on product.Id equals details.ProductId
                          select new
                          {
                              Product = product,
                              ProductDetails = details
                          };

var result = productsWithDetails.ToList();

------------------------------------------------------------------------------------------------------------------------------------------
Q22. What is the strategy to migrate from .net framework to .net core?

Answer:
At times we have to migrate our old application from .net framework to .net core for containerization, plateform independent etc. 
Below are the points we have to take care while migrating. 

So migration will happen in 3 phases. 
1. Data/Model layer: Migrate the Entity framework to EF core. One way is to upgrade the asp.net EF to EF 6 which is much similar to EF core. 
2. Business/ Controller layer: .net classes to .net core classes. 
3. UI layer: Asp.net page to Asp.net core pages. 


------------------------------------------------------------------------------------------------------------------------------------------
Q23. What are the 3 parts of JWT?

Answer:
JWT - Json Web Token.
JWT token consists of 3 parts separated by . dots
1. Header
2. Payload. 
3. Signature

Header - contains two part type and algo. 
{
  "alg": "HS256",
  "typ": "JWT"
}

Payload: Usually contains the information about the user like role, name, status etc. These are called claims ie in payload we have claims details like role, name, status etc
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature: To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)


------------------------------------------------------------------------------------------------------------------------------------------
Q24. How JWT works? How we get values of JWT token?

Answer:
In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned.
Whenever the user wants to access a protected route, it should send the JWT, typically in the Authorization header using the Bearer schema. Therefore the content of the header should look like the following.

Authorization: Bearer <token>




------------------------------------------------------------------------------------------------------------------------------------------
Q25. What will be your approach in case you want to call a manual stored procedure from your dot net code with Entity Framework?

Answer:

1) If the stored procedure is doing an update/insert/delete (not returning entities), I’d use Database.ExecuteSqlCommand in EF6 or Database.ExecuteSqlRaw in EF Core.

2) If the stored procedure returns rows that map to an entity, I’d use SqlQuery in EF6 or FromSqlRaw in EF Core. 

Thursday, February 18, 2021

EF core with .net core 3.1

Steps to use EF Core in project.  (easy)

>> Go to Nuget packages and install "Microsoft.EntityFramework.SqlServer". This will install few more dependent packages with it. 
>> Right click and create a folder named "Database"
>> Add a class and named it AppDbContext.cs (it could be any name)
>> Inherit the above class with "DbContext" class. "DbContext" class is available  when we use 'using Microsoft.EntityFrameworkCore;' on top of a class file. 
>> Create entities (tables) classes in model folder (or in same folder)
>> Create DB set property for above model class in AppDbContext class.

    public class AppDBContext: DbContext
    {
        public AppDBContext(DbContextOptions<AppDBContext> options) : base(options)
        {
        }

        public DbSet<Student> Students { get; set; }
    }

>> Now register the DBContext class in startup.ConfigureService method.

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDBContext>(options =>
               options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        }

Saturday, November 28, 2020

Q16-Q20

Q16. Difference between concurrency and parallelism?
Q17. What is httpclientFactory?
Q18. Example of Nuget Middlewares, System inbuild middlewares?
Q19. Example of custom middlewares. 
Q20. Steps to implement Repository pattern with EntityFrameworkCore in dotnet 8?

=======================================================================
Q16. Difference between concurrency and parallelism?

Answer:
Concurrency - It means executing multiple tasks on same core. In this case the same core switches between multiple tasks and giving a feel that multiple tasks are excuting in parallel but in actual core is executing all of them little by little. Concurrency is a feel of parallelism. 

1. It is used to bring non blocking architecture. Means non of your task is blocked and the end user will keep seeing output of other tasks. The goal of this is not performance but making the feel of application as non blocking. This ensure to make application user friendly. 
2. its a async-await feature. In which the caller(the parent method, usually method of main class) doesn't wait for completion of child method  and move ahead. on getting data at await level, method thread will come back. 
3. Single thread picking multiple items to keep non blocking code. No good in performance but caller will not hanged up and remain unblocked. 

Parallelism -  Executing multiple tasks on multiple cores. 
1. It is used to bring parallelism 
2. Task is the feature. Threads are used as concept. Now it will create different threads for differnt task. 
3. It uses all cores present in system and give good performance. Multi threading is another word for it. 

For code level example and better understanding visit below
=======================================================================
Q17. What is httpclientFactory?

Answer:
A new HttpClientFactory feature comes with ASP.NET Core 2.1 which helps to solve some common problems that developers may run into when using HttpClient instances to make external web requests from their applications.

The main issue is when you create too many HttpClients within your code which can in turn into a problem ie socket Exhaustion. Where you have basically used up too many sockets too fast. There is a limit on how many sockets you can have open at one time. When you dispose of the HttpClient, the connection it had open remains open for up to 240 seconds in a TIME_WAIT state (in case any packets from the remote server still come through).

WATCH the youtube link for quick review. (IMP video)



=======================================================================
Q18. Example of Nuget Middlewares, System inbuild middlewares?

Answer:

Nuget:
EntityFrameworkCore
CORS

Framework:
UseStaticFiles
UseRouting
UseAuthorization
UseAuthentication

=======================================================================
Q19. Example of custom middlewares. 

Answer:
We have custom middleware for acknowledgement. We have 3rd party service which is giving inbound json data to our api. We have a middleware which send acknowledge of reading that json file and processing all the data correctly or not. so that 3rd party service is aware of proper data flow.  

=======================================================================
Q20. Steps to implement Repository pattern with EntityFrameworkCore in dotnet 8?

Answer:
1. Create dotnet core project and install nuget packages

dotnet new webapi -n MyNewApp
cd MyNewApp

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

2. Define entity class and create a DBContext class. Give reference of entity class as DbSet property in DBContexct class. 

3. Define IMyRespository and implement MyRepositoryClass

4. Register the Repository in DIContrainer in program.cs class
5. Inject the Repository in Controller Constructor and use it for calling methods. 
=======================================================================

Q36-Q40(EF)

Q36.  What is the difference between Include and Join in entity framework? Q37. What will be your approach in case you want to call a manual...