You are on page 1of 15

1. Explain Dependency Injection.

Dependency injection is a design pattern that allows you to inject dependencies


(objects) into your code at runtime.
In ASP.NET Core, the built-in DI container manages the creation and lifetime of
these dependencies.
This means your code doesn't need to create or manage them directly, leading to
looser coupling and more testable code.

2.What are the benefits of ASP.NET Core?


Cross-platform: Develop for Windows, macOS, Linux, & various architectures.
Lightweight & performant: Blazing fast execution & minimal resource footprint.
Unified APIs: Build web UIs & APIs with a consistent, flexible approach.
Modular & testable: Easy to customize & test, promoting code maintainability.
Cloud-friendly: Integrates seamlessly with cloud platforms like Azure.
Blazingly fast: Optimized for modern web frameworks & APIs.
Open-source & community-driven: Access to vast resources & ongoing development.

3. Explain the request processing pipeline in ASP.NET Core.


The ASP.NET Core request processing pipeline, also called the "middleware
pipeline," is a series of modular components called "middleware" that handle an
incoming HTTP request in sequence. Each middleware performs a specific task before
passing the request to the next one, like authentication, logging, or routing.

4. What is a Request delegate and how is it used?


In ASP.NET Core, a Request delegate is a function that processes and handles an
incoming HTTP request. It's the core building block of the request processing
pipeline, which is essentially a series of middleware components that handle the
request one after the other.

5. Explain how Configuration works in ASP.NET Core and reading values from the
appsettings.json file.
ASP.NET Core config lives in key-value pairs across sources like files
(appsettings.json) and environment. Providers like JSON or environment vars read
these pairs and build a unified view. Access values by key using IConfiguration to
control app behavior without hardcoding.

6. Explain how routing works in ASP.NET Core MVC applications.


In ASP.NET Core MVC, routing acts like a map, directing incoming URLs to the right
controller action.
It uses two key ingredients: route templates that define possible URL patterns and
middleware that scan requests against those patterns.
When a match is found, the corresponding controller action is invoked, handling the
request and generating a response.

7. What is the role of middleware in ASP.NET Core?


Intercepts HTTP requests and responses
Processes requests in a configurable pipeline
Offers built-in features like authentication, logging, and compression
Allows custom middleware for specific application needs
Extends functionality without modifying the core framework

8. Explain the Logging system in .NET Core and ASP.NET Core.


Logging system in .NET Core:
.NET Core's logging system is a flexible tool for recording application events.
It uses the ILogger interface and ILoggerFactory to generate and manage logs.
You can send logs to various destinations like consoles, files, and databases.
Different log levels like Information and Error control message severity.
The system integrates with dependency injection and web frameworks, making it easy
to configure and use throughout your application.
Logging system in ASP.NET Core:
ASP.NET Core's logging system uses structured messages and flexible configuration.
It offers pre-built providers like console and debug, but you can extend it with
custom sinks like databases or third-party tools.
Dependency injection provides ILogger instances for code to log application events,
errors, and performance details, helping you troubleshoot and monitor your web app
effectively.

9. Explain strategies for handling errors and exceptions in ASP.NET Core


applications.
Error and exception handling are crucial for building robust and reliable ASP.NET
Core applications. Here are some key strategies to consider:

Middleware: Global error handling with specific responses, logging, and custom
error pages.
Try/Catch: Localized error handling for specific scenarios and resource cleanup.
Exception Filters: Intercept and handle exceptions before reaching the middleware.
Descriptive Errors: Throw specific exceptions with clear messages for better
debugging.
Logging: Capture all exceptions for analysis and later troubleshooting.

10. How can ASP.NET Core APIs be used and accessed from a class library project?
Accessing ASP.NET Core APIs from a class library involves two key steps:

Target the ASP.NET Core Shared Framework: This ensures your library shares the same
base framework as an ASP.NET Core application, allowing seamless API usage.
Reference relevant NuGet packages: For specific ASP.NET Core functionalities,
install the corresponding NuGet packages within your class library project. This
grants access to specific API components you need.

Reading Values from appsettings.json:


Once the configuration is built, you can access values from appsettings.json using
the IConfiguration interface injected in your classes or accessed through the
Host.Configuration property.
You can retrieve values by their key using methods like GetValue<T>("key"), where T
is the expected type of the value.

11. Describe Model Binding in ASP.NET Core.


In ASP.NET Core, model binding is a powerful feature that bridges the gap between
user input and your application logic.
It automatically maps data from an HTTP request (like forms, query strings, or JSON
bodies) to C# model objects used in your controller actions.
This simplifies development by removing the need for manual data parsing and
validation.

C#
---

1. Differentiate between managed and unmanaged code


Managed Code - Managed Code is developed within the .NET framework. CLR directly
executes such code by using managed code execution. Any language written in
the .NET framework is considered to be managed code.

Unmanaged Code - Unmanaged code is any code developed outside the .NET framework.
Unmanaged applications are not executed by CLR. Some languages like C++ can write
unmanaged applications such as an application for accessing the low-level functions
of the operating system. Some examples of unmanaged code include background
compatibility with the code of VB, ASP, and COM.

2. What is the difference between Task and Thread?


Following are the differences between Task and Thread in C#:

Task is an object used in the Task Parallel Library (TPL) to represent an


asynchronous operation, while a Thread is a separate path of execution in a
program. Tasks are a higher level of abstraction than threads and are used to
manage the execution of code in parallel.

Tasks are easier to use and manage than threads, and they can also be used to
provide more efficient resource utilization. Threads on the other hand, provide a
lower level of abstraction and are used to execute code directly in the processo
Following are the differences between Task and Thread in C#:

3.What is a Destructor in C# and when is it used?

A destructor is a special method in C# that is automatically called when an object


is destroyed. It is used to free up any resources that the object may have been
using, such as memory or files. Destructors are usually implemented in a class and
are denoted by the keyword ~ followed by the class name.

For example, if a class called MyClass was to have a destructor, it would be


declared as follows: ~MyClass().

4.Differentiate between ref and out keywords.

The main difference between ref and out keywords in C# is that ref requires that
the variable be initialized before being passed to the method whereas out keyword
doesn’t require the variable to be initialized before being passed to the method.

5. How is encapsulation implemented in C#?

You can implement encapsulation by using access specifiers that define the scope
and visibility of a class member. Some access specifiers are as follows:

Public access specifier: It allows a class to expose its member functions and
variables to other objects and functions. It allows access to any public member
from outside the class.
Private access specifier: It allows a class to hide its member functions and
variables from other objects and functions. It allows only functions of the same
class to access its private members.
Protected access specifier: It allows a child class to access its base class's
member function and variables, thus helping in inheritance implementation.

6. What do you understand about method shadowing or method hiding in C#?

Shadowing or method hiding in C# is a VB.Net concept hiding the implementation of


the base class method. You can achieve method shadowing using the 'new' keyword. If
a method does not override the derived method, it hides it.

7. What are generics in C#.NET?


Generics are classes that allow you to define classes and methods with a
placeholder. The purpose of generics is to make reusable code classes. These
classes decrease code redundancy and increase performance and type safety.

Generics promotes the usage of parameterized types. You can also create collection
classes using generic. System.Collections.The generic namespace is used instead of
classes to create a generic collection.

8. What do you understand about dependency injection?


You can de-couple tightly linked classes using the dependency injection. Thus, it
reduces the direct dependency of classes upon each other. You can achieve
dependency injection via the following:

Constructor dependency
Property dependency
Method dependency

9.What do you understand about Polymorphism in C#?


This is one of the most commonly asked C# interview questions and answers for
experienced professionals. Polymorphism is one of the three main pillars of object-
oriented programming after encapsulation and inheritance.

The term polymorphism means "many shapes." It occurs when there are many classes
related to each other by inheritance.

For instance, at runtime, derived class objects may be treated as base class
objects in places like collections/ method parameters/ arrays. In such
polymorphism, declared and runtime types of objects are different. Thus,
polymorphism allows a class to have multiple implementations with the same name.

10. Is it possible to serialize hashtables?


No, you cannot serialize a hashtable because the .NET Framework doesn't allow the
serialization of an object that implements the IDictionary interface.

11. What is Satellite Assembly?


A compiled library (DLL) containing localizable resources specific to a given
culture like strings and bitmaps is referred to as a Satellite Assembly. You can
use satellite assemblies while creating a multilingual UI application.

12. What are the advantages of using partial classes?


The major advantages of using partial classes are as follows:

They allow multiple developers to work on the same class easily.


The code generators mainly use them to keep different concerns separate.
It allows one developer to define the method while the other developer can
implement it.

13. What is string interpolation in C#?


String Interpolation in C# allows to create formatted strings with readable and
convenient syntax. You can create an interpolation string containing interpolation
expressions using the $ special character. On resolving, the interpolation string
replaces the interpolation expression with the string representation of the
interpolation item.

14. What are Covariance and Contravariance in C#?


While covariance allows a method to have a return type, a subtype of the one
defined in the delegate, contravariance allows a method to have a parameter type,
i.e., a base type of the one defined in the delegate type.
15. What do you understand about boxing and unboxing?
16. Is it possible to store mixed data types such as string, int, float, and char
in one array?
Yes, we can store.

17. What is a race condition in C#?


A race condition is an undesirable situation that occurs when a device or system
attempts to perform two or more operations at the same time, but because of the
nature of the device or system, the operations must be done in the proper sequence
to be done correctly.

18. How would you force Garbage Collection?

Collect(Int32, GCCollectionMode, Boolean, Boolean)

Forces a garbage collection from generation 0 through a specified generation, at a


time specified by a GCCollectionMode value, with values that specify whether the
collection should be blocking and compacting.

19. What is lock () in C#? What is lock and Monitor?


How is Lock different from Monitor in C#?

The lock statement acquires the mutual-exclusion lock for a given object, executes
a statement block, and then releases the lock. While a lock is held, the thread
that holds the lock can again acquire and release the lock. Any other thread is
blocked from acquiring the lock and waits until the lock is released.

A lock typically prevents more than one entity from accessing a shared resource.
Each object in the C# language has an associated lock, also referred to as a
monitor, which a thread obtains by using a synchronized method or block of code.

Both the lock statement and the Monitor class provide similar functionality by
ensuring exclusive access to shared resources. However, the Monitor class offers
more flexibility, allowing you to use other methods like Monitor. Wait and Monitor.
Pulse for more advanced synchronization scenarios.

What are the different types of locks in C#?

There are two types of locks: exclusive and nonexclusive.


Exclusive locks only allow one thread to access a certain piece of code
exclusively. ...
Nonexclusive locks, on the other hand, allow a limited number of threads to access
a single resource or piece of code at the same time. ...
NET Lock / Monitor.
NET Mutex Lock.

20. How is Var different from Dynamics in C#?


21. When would you use Tuples in C#?
22. How would you create a responsive UI without impacting users?
23. Why is the singleton pattern referred to as an anti-pattern?
24. How would you use Nullable Types in .NET?
25. How would you implement a singleton design pattern in C#?
26. What are the key differences between the "throw" and "throw ex" in .NET?

Angular
--------
1. What is data binding? Which type of data binding does Angular deploy?
Data binding is a phenomenon that allows any internet user to manipulate Web page
elements using a Web browser. It uses dynamic HTML and does not require complex
scripting or programming. We use data binding in web pages that contain interactive
components such as forms, calculators, tutorials, and games. Incremental display of
a webpage makes data binding convenient when pages have an enormous amount of data.

Angular uses the two-way binding. Any changes made to the user interface are
reflected in the corresponding model state. Conversely, any changes in the model
state are reflected in the UI state. This allows the framework to connect the DOM
to the Model data via the controller. However, this approach affects performance
since every change in the DOM has to be tracked.

2. What are Single Page Applications (SPA)?

Single-page applications are web applications that load once with new features just
being mere additions to the user interface. It does not load new HTML pages to
display the new page's content, instead generated dynamically. This is made
possible through JavaScript's ability to manipulate the DOM elements on the
existing page itself. A SPA approach is faster, thus providing a seamless user
experience.

3. What are decorators in Angular?


Decorators are a design pattern or functions that define how Angular features work.
They are used to make prior modifications to a class, service, or filter. Angular
supports four types of decorators, they are:

Class Decorators
Property Decorators
Method Decorators
Parameter Decorators

4. What are Templates in Angular?


Angular Templates are written with HTML that contains Angular-specific elements and
attributes. In combination with the model and controller's information, these
templates are further rendered to provide a dynamic view to the user.

5. What are Annotations in Angular?


Annotations in Angular are used for creating an annotation array. They are the
metadata set on the class that is used to reflect the Metadata library.

6. What are Pipes in Angular?


Pipes are simple functions designed to accept an input value, process, and return
as an output, a transformed value in a more technical understanding. Angular
supports several built-in pipes. However, you can also create custom pipes that
cater to your needs.

Some key features include:

Pipes are defined using the pipe “|” symbol.


Pipes can be chained with other pipes.
Pipes can be provided with arguments by using the colon (:) sign.

7. What are Pure Pipes?


These pipes are pipes that use pure functions. As a result of this, a pure pipe
doesn't use any internal state, and the output remains the same as long as the
parameters passed stay the same. Angular calls the pipe only when it detects a
change in the parameters being passed. A single instance of the pure pipe is used
throughout all components.

8. What are Impure Pipes?


For every change detection cycle in Angular, an impure pipe is called regardless of
the change in the input fields. Multiple pipe instances are created for these
pipes. Inputs passed to these pipes can be mutable.

9. What is an ngModule?
NgModules are containers that reserve a block of code to an application domain or a
workflow. @NgModule takes a metadata object that generally describes the way to
compile the template of a component and to generate an injector at runtime. In
addition, it identifies the module's components, directives, and pipes, making some
of them public, through the export property so that external components can use
them.

10. What are filters in Angular? Name a few of them.


Filters are used to format an expression and present it to the user. They can be
used in view templates, controllers, or services. Some inbuilt filters are as
follows.

date - Format a date to a specified format.


filter - Select a subset of items from an array.
Json - Format an object to a JSON string.
limitTo - Limits an array/string, into a specified number of elements/characters.
lowercase - Format a string to lowercase.

11. What is view encapsulation in Angular?


View encapsulation defines whether the template and styles defined within the
component can affect the whole application or vice versa. Angular provides three
encapsulation strategies:

Emulated - styles from the main HTML propagate to the component.


Native - styles from the main HTML do not propagate to the component.
None - styles from the component propagate back to the main HTML and therefore are
visible to all components on the page.

12. What are controllers?


AngularJS controllers control the data of AngularJS applications. They are regular
JavaScript Objects. The ng-controller directive defines the application controller.

13. What do you understand by scope in Angular?


The scope in Angular binds the HTML, i.e., the view, and the JavaScript, i.e., the
controller. It as expected is an object with the available methods and properties.
The scope is available for both the view and the controller. When you make a
controller in Angular, you pass the $scope object as an argument.

14. What is String Interpolation in Angular?


String Interpolation is a one-way data-binding technique that outputs the data from
TypeScript code to HTML view. It is denoted using double curly braces. This
template expression helps display the data from the component to the view.

{{ data }}

15. What are Template statements?


Template statements are properties or methods used in HTML for responding to user
events. With these template statements, the application that you create or are
working on, can have the capability to engage users through actions such as
submitting forms and displaying dynamic content.

For example,

<button (click)="deleteHero()">Delete hero</button>

The template here is deleteHero. The method is called when the user clicks on the
button.

16. What are Promises and Observables in Angular?


While both the concepts deal with Asynchronous events in Angular, Promises handle
one such event at a time while observables handle a sequence of events over some
time.

Promises - They emit a single value at a time. They execute immediately after
creation and are not cancellable. They are Push errors to the child promises.

Observables - They are only executed when subscribed to them using the subscribe()
method. They emit multiple values over a period of time. They help perform
operations like forEach, filter, and retry, among others. They deliver errors to
the subscribers. When the unsubscribe() method is called, the listener stops
receiving further values.

17. What is ngOnInit? How is it defined?


ngOnInit is a lifecycle hook and a callback method that is run by Angular to
indicate that a component has been created. It takes no parameters and returns a
void type.

export class MyComponent implements OnInit {

constructor() { }

ngOnInit(): void {

//....

18. How to use ngFor in a tag?


The ngFor directive is used to build lists and tables in the HTML templates. In
simple terms, this directive is used to iterate over an array or an object and
create a template for each element.

<ul>

<li *ngFor = "let items in itemlist"> {{ item }} </li>

</ul>

“Let item” creates a local variable that will be available in the template
“Of items” indicates that we are iterating over the items iterable.
The * before ngFor creates a parent template.

19. Explain the lifecycle hooks in Angular

In Angular, every component has a lifecycle. Angular creates and renders these
components and also destroys them before removing them from the DOM. This is
achieved with the help of lifecycle hooks. Here's the list of them -

ngOnChanges() - Responds when Angular sets/resets data-bound input properties.


ngOnInit() - Initialize the directive/component after Angular first displays the
data-bound properties and sets the directive/component's input properties/
ngDoCheck() - Detect and act upon changes that Angular can't or won't detect on its
own.
ngAfterContentInit() - Responds after Angular projects external content into the
component's view.
ngAfterContentChecked() - Respond after Angular checks the content projected into
the component.
ngAfterViewInit() - Respond after Angular initializes the component's views and
child views.
ngAfterViewChecked() - Respond after Angular checks the component's views and child
views.
ngOnDestroy - Cleanup just before Angular destroys the directive/component.

20. What is Eager and Lazy loading?


Eager loading is the default module-loading strategy. Feature modules under Eager
loading are loaded before the application starts. This is typically used for small
size applications.

Lazy loading dynamically loads the feature modules when there's a demand. This
makes the application faster. It is used for bigger applications where all the
modules are not required at the start of the application.

21.What is Bootstrap? How is it embedded into Angular?


Bootstrap is a powerful toolkit. It is a collection of HTML, CSS, and JavaScript
tools for creating and building responsive web pages and web applications.

There are two ways to embed the bootstrap library into your application.

Angular Bootstrap via CDN - Bootstrap CDN is a public Content Delivery Network. It
enables you to load the CSS and JavaScript files remotely from its servers.
Angular Bootstrap via NPM - Another way to add Bootstrap to your Angular project is
to install it into your project folder by using NPM (Node Package Manager).
npm install bootstrap

npm install jquery

22. How do you share data between components in Angular?


Sharing data between components in Angular is simple and easy. To share data, all
you need to do is use the Angular CLI to generate a new service. This service can
be injected into any component and will allow the components to share data.

To generate a new service, use the following Angular CLI command:

ng generate service my-data-service

This will create a new service file called my-data-service.ts in the src/app
folder.

Inject the service into any component that needs to share data:

import { MyDataService } from './my-data.service';

constructor(private myDataService: MyDataService) { }


Once injected, the service will be available in the component as
this.myDataService.

To share data between components, simply use the setData() and getData() methods:

this.myDataService.setData('some data');

const data = this.myDataService.getData();

SQL:
--------

1. What do you know about the stuff() function?


The stuff() function deletes a part of the string and then inserts another part
into the string, starting at a specified position.

Syntax:

1
STUFF(String1, Position, Length, String2)
Here, String1 is the one that will be overwritten. The position indicates the
starting location for overwriting the string. Length is the length of the
substitute string, and String2 is the string that will overwrite String1.

Example:

1
select stuff(‘SQL Tutorial’,1,3,’Python’)
This will change ‘SQL Tutorial’ to ‘Python Tutorial’

Output:

1
Python Tutorial

2. What do you understand about a temporary table? Write a query to create a


temporary table
A temporary table helps us store and process intermediate results. Temporary tables
are created and can be automatically deleted when they are no longer used. They are
very useful in places where temporary data needs to be stored.

Syntax:

1
2
3
4
5
6
7
CREATE TABLE #table_name();
The below query will create a temporary table:
create table #book(b_id int, b_cost int)
Now, we will insert the records.
insert into #book values(1,100)
insert into #book values(2,232)
select * from #book
3. What is a database cursor? How to use a database cursor?
A database cursor is a control that allows you to navigate around a table’s rows or
documents. It can be referred to as a pointer for a row in a set of rows. Cursors
are extremely useful for database traversal operations such as extraction,
insertion, and elimination.

After any variable declaration, DECLARE a cursor. A SELECT statement must always be
aligned with the cursor declaration.
To initialize the result set, OPEN statements must be called before fetching the
rows from the result table.
To grab and switch to the next row in the result set, use the FETCH statement.
To deactivate the cursor, use the CLOSE expression.
Finally, use the DEALLOCATE clause to uninstall the cursor description and clear
all the resources associated with it.

4. What is a Deadlock or a live Deadlock, and how do you resolve it?


A deadlock is a situation where a set of processes are blocked because each process
is holding the resource and waiting for the other resource. A live deadlock is just
like a deadlock-like situation where the processes block each other with a repeated
state change yet make no progress.

There are several ways to prevent a deadlock or live deadlock situation:

Acquired multiple locks for a thread.


Abort and restart the process.
Timeouts
Transaction Rollback

5. What are some common clauses used with SELECT queries in SQL?
There are many SELECT statement clauses in SQL. Some of the most commonly used
clauses with SELECT queries are as follows:

FROM
The FROM clause defines the tables and views from which data can be interpreted.
The tables and views listed must exist at the time the question is given.
WHERE
The WHERE clause defines the parameters that are used to limit the contents of the
results table. You can test for basic relationships or for relationships between a
column and a series of columns using subselects.
GROUP BY
The GROUP BY clause is commonly used for aggregate functions to produce a single
outcome row for each set of unique values in a set of columns or expressions.
ORDER BY
The ORDER BY clause helps in choosing the columns on which the table’s result
should be sorted.
HAVING
The HAVING clause filters the results of the GROUP BY clause by using an aggregate
function.

6. How can you copy data from one table to another table?
We have to copy this data into another table. For this purpose, we can use the
INSERT INTO SELECT operator. Before we go ahead and do that, we will have to create
another table that will have the same structure as the above-given table.

Syntax:

create table employee_duplicate(


e_id int,
e_name varchar(20),
e_salary int,
e_age int,
e_gender varchar(20)
e_dept varchar(20)
)
For copying the data, we will use the following query:

insert into employee_duplicate select * from employees

7. What is the difference between BETWEEN and IN operators in SQL?


The BETWEEN operator is employed to identify rows that fall within a specified
range of values, encompassing numerical, textual, or date values. It returns the
count of values that exist between the two defined boundaries.

On the other hand, the IN operator serves as a condition operator utilized for
searching values within a predetermined range. When multiple values are available
for selection, the IN operator is utilized.

8. What is the difference between HAVING and WHERE clauses?


The main difference between the ‘HAVING’ and ‘WHERE’ clauses in SQL is that the
‘WHERE’ clause operates on individual rows of data, while the ‘HAVING’ clause is
used to filter aggregated data. The ‘WHERE’ clause cannot be used with aggregate
functions, whereas the ‘HAVING’ clause specifically filters results based on
aggregate conditions.

Entity Framework
------------------
1. What are the main components of Entity Framework Architecture?
Entity Framework Architecture consists of the following components:

Entity Data Model (EDM): EDMs abstract logical or relational schema and expose
conceptual schema of data with a three-layered model, i.e., Conceptual (C-Space),
Mapping (C-S Space), and Storage (S - Space).

LINQ to Entities (L2E): L2E is basically a query language generally used to write
queries against the object model. The entities defined in the conceptual model are
returned by L2E.

Entity SQL (E-SQL): Similar to L2E, E-SQL is another query language (for EF6 only).
The developer must however learn it separately since it is more difficult than L2E.
Internally, E-SQL queries are translated or converted to data store-dependent SQL
queries. EF is used for converting E-SQL queries to their respective datastore
queries, such as T-SQL.

Entity Client Data Provider: This layer's main task is to convert E-SQL or L2E
queries into SQL queries that the database understands. In turn, the ADO.Net data
provider sends and retrieves data from the database.

Net Data Provider: It uses standard ADO.NET to enable interaction with the
database.

Object Service: It is a service that facilitates access to a database, and returns


data for analysis when necessary. By using it, you are able to translate data
coming from entity clients into entity object structures.
5. Explain different parts of the entity data model.

Conceptual Model: It is also referred to as the Conceptual Data Definition Language


Layer (C-Space). Typically, it consists of model classes (also known as entities)
and their relationships. Your database table design will not be affected by this.
It makes sure that business objects and relationships are defined in XML files.

Mapping Model: It is also referred to as the Mapping Schema Definition Language


layer (C-S Space). Information about how the conceptual model is mapped to the
storage model is usually included in this model. In other words, this model enables
the business objects and relationships defined at the conceptual layer to be mapped
to tables and relationships defined at a logical layer.

Storage Model: It is also referred to as the Store Space Definition Language Layer
(S-Space). Schematically, it represents the storage area in the backend. Therefore,
the storage model is also known as a database design model that is composed of
tables, keys, stored procedures, views, and related relationships.

6. Explain what the .edmx file contains.


First of all, a database lets you reverse engineer a model from an existing
database. Entity Framework Designer is used to view and edit models stored and
created in EDMX files (.edmx extensions). Using the EDMX file, you automatically
generate classes that you can interact with within your application.

EDMX files represent conceptual models, storage models, and their mappings. This
file contains all the mapping information between SQL tables and objects. In
addition, it also includes essential information required for rendering models
graphically with ADO.NET Entity Data Designer. Furthermore, it is divided into
three divisions, CSDL, MSL, and SSDL.

7. What are different types of Entity framework approaches?


Three different approaches to implement Entity Framework are as follows:

Code First Approach: The Code First approach primarily uses classes to create the
model and its relations, which are then used to create a database. This way,
developers can work in an object-oriented manner without considering the database
structure. By following this model, developers first write POCO classes and then
use these classes to create the database. Code First is the method used by most
developers using Domain-Driven Design (DDD).

Model First Approach: In contrast, the Model First approach uses ORM to build model
classes and their relationships. Following the successful creation of the model
classes and relationships, the physical database is created using these models.

Database-First Approach: In Entity Framework, Database First approach is used to


build entity models based on existing databases and reduce the amount of code
required. By using this approach, domain and context classes can be created based
on existing classes.

8. Which according to you is considered the best approach in Entity Framework?


It is impossible to define one approach as the optimal approach when using the
Entity Framework. Project requirements and the type of project determine which
development approach should be used. Database First is a good approach if there is
a database present. Model First is the optimal choice if no database and model
classes exist. As long as the domain classes are available, the Code First method
is the best choice.

9. What do you mean by the term navigation property in the entity framework?
A foreign key relationship in the database is represented by the navigation
property supported by the Entity Framework. It is possible to specify relationships
between entities in a database using this property type. Relationships are defined
in a way as to remain coherent in object-oriented code.

10. What are different entity states in EF?


There are five possible states where an entity can exist:

Added: It is a state in which an entity exists within the context but does not
exist within the database. When the user invokes the SaveChanges method, DbContext
usually generates an INSERT SQL query to insert the data into the database. Upon
successful completion of the SaveChanges method, the entity's state changes to
unchanged.

Deleted: This state indicates that the entity is marked for deletion has not been
removed from the database. Also, it indicates the existence of the entity in the
database. When the user invokes the SaveChanges method, DbContext usually generates
a DELETE SQL query to delete or remove the entity from the database. Upon
successful completion of the delete operation, DbContext removes the entity.

Modified: When the entity is modified, its state becomes Modified. Also, it
indicates the existence of the entity in the database. When the user invokes the
SaveChanges method, DbContext usually generates an UPDATE SQL query to update the
entity from the database. Upon successful completion of the SaveChanges method, the
entity's state changes to unchanged.

Unchanged: Since the context retrieved the entity's property values from the
database, the values have not changed. This entity is ignored by SaveChanges.
Detached: This state indicates that the entity is not tracked by the DbContext. If
an entity was created or retrieved outside the domain of the current instance of
DbContext, then its entity state will be Detached.

11. Write the importance of the T4 entity in Entity Framework.


In Entity Framework code generation, T4 files are crucial. EDMX XML files are read
by T4 code templates, which generate C# behind code. The generated C# behind code
consists only of your entity and context classes.

12. Explain how EF supports transactions.


The SaveChanges() method in EF always wraps any operation involving inserting,
updating, or deleting data into a transaction. Hence, you do not have to explicitly
open the transaction scope.

13. What do you mean by Deferred Execution in EF?


Deferred Execution refers to the process of delaying the evaluation of an
expression until its realized value is actually required. As a result, performance
is greatly improved since unnecessary execution is avoided. Queries are deferred
until the query variable or query object is iterated over a loop.

Explain the term dbcontext and dbset.


DbSet: An entity set is represented by a DbSet class that can be used for creating,
reading, updating, and deleting operations on it. Those DbSet type properties,
which map to database tables and views, must be included in the context class
(derived from DbContext).

DbContext: It is considered an essential class in EF API that bridges the gap


between an entity or domain class and the database. Communication with the database
is its primary responsibility.

14. Explain the role of Pluralize and Singularize in the entity framework.
Objects in Entity Framework are primarily assigned names using Pluralize and
Singularize. This feature is available when adding a .edmx file. Entity Framework
automatically assigns the Singular or Plural coding conventions when using this
feature. In convention names, an additional 's' is added if there is more than one
record in the object.

15.What is the difference between Dapper and Entity Framework?


.NET developers are allowed to work with relational data using domain-specific
objects by object-relational mappers such as Entity Framework (EF) and Dapper.
Performance-wise, Dapper is the King of Micro ORMs.

Dapper: A simple micro ORM, Dapper is considered a powerful system used for data
access in the .NET world. As a means to address and open-source their issues, the
Stack Overflow team created Dapper. Adding this NuGet library to your .NET project
allows you to perform database operations. In terms of speed, it is the king of
Micro ORMs and is almost as fast as using raw ADO.NET data readers.
Entity Framework: It is a set of .NET APIs used in software development for
performing data access. It is Microsoft's official tool for accessing data.
Comparison

According to NuGet downloads and performance, Dapper is the world's most popular
Micro ORM. In contrast, Entity Framework is significantly slower than Dapper.
In comparison to other ORMs, such as the Entity Framework, Dapper does not generate
as much SQL, but it does an excellent job mapping from database columns to CLR
properties.
Since Dapper uses RAW SQL, it can be difficult to code, especially when multiple
relationships are involved, but when a lot of data is involved and performance
matters, it is worth the effort.
Since Dapper uses IDbConnection, developers can execute SQL queries to the database
directly rather than put data in other objects as they do in Entity Framework.

16. Explain database concurrency and the way to handle it.


Database concurrency in EF means that multiple users can simultaneously modify the
same data in one database. Concurrency controls help safeguard data consistency in
situations like these.

Optimistic locking is usually used to handle database concurrency. We must first


right-click on the EDMX designer and then change the concurrency mode to Fixed in
order to implement locking. With this change, if there is a concurrency issue, we
will receive a positive concurrency exception error.

You might also like