Entity Framework

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Difference between ADO.NET and ASP .

NET:
ADO.NET and ASP.NET are two different technologies used in .NET development, with
different purposes and functionalities.

ADO.NET is a data access technology that provides a set of classes and interfaces to
interact with various data sources such as databases, XML files, and web services. It is
used to access and manipulate data from databases and other data sources using a set of
objects and classes such as Connection, Command, DataReader, DataSet, and
DataAdapter. ADO.NET provides a low-level access to data and requires more coding
effort to manage data access.

ASP.NET, on the other hand, is a web application framework used to build dynamic web
applications and web services. It provides a set of libraries and tools for building web
applications, including web forms, MVC, and web API. ASP.NET provides a high-level
abstraction over HTTP and allows developers to build web applications using the
Model-View-Controller (MVC) pattern. It includes a set of controls and components that
simplify web development, such as server controls, validation controls, and
authentication controls.

In summary, ADO.NET is a data access technology used to access and manipulate data
from various data sources, while ASP.NET is a web application framework used to build
web applications and services.

Entity Framework:
Entity Framework (EF) is an object-relational mapping (ORM) framework for .NET
applications. It is a set of libraries and tools that enable developers to work with data in
a database using .NET objects. EF simplifies data access by providing an abstraction
layer over the database schema, allowing developers to work with high-level domain-
specific objects instead of low-level database tables and columns.

The Entity Framework is built on top of ADO.NET, which provides low-level access to
data. It supports various databases such as SQL Server, MySQL, Oracle, and PostgreSQL,
and it allows developers to use LINQ to query data.

EF provides various features such as change tracking, lazy loading, and automatic code
generation. It also provides support for transactions, concurrency, and stored
procedures.

EF is a powerful tool for developers as it simplifies the process of accessing and


manipulating data and allows for more efficient development of data-driven
applications.
ENTITY FRAMEWORK

What is Entity Framework?


We (developers) used to frequently write ADO.NET code or Enterprise Data Access
Block in Dot NET 3.5 to save or retrieve application data from the underlying database.
Microsoft has provided a framework called "Entity Framework" to automate all these
database-related activities for your application. Entity Framework is a Microsoft-
supported open-source ORM framework for.NET applications. It enables developers to
work with data using objects of domain-specific classes without focusing on the
underlying database tables and columns where this data is stored.

ORM in C#:
In C#, ORM stands for Object-Relational Mapping. It's a programming technique used to
map objects from object-oriented programming languages like C# to relational database
tables.

With ORM, developers can interact with databases using objects and classes, which
makes database operations simpler and closely aligned with the object-oriented
principles of the programming language.

Popular ORM frameworks in C# include Entity Framework, NHibernate, Dapper, and


others. These frameworks provide tools and libraries to facilitate the mapping between
database tables and C# objects, as well as utilities for querying and manipulating data
using object-oriented syntax.

Why Entity Framework in .NET Applications?


 Entity Framework is an ORM tool, and ORM tools are primarily used to boost
developer productivity by eliminating the redundant task of performing CRUD
operations against a database in a.NET application.
 Entity Framework can generate the necessary database commands for doing the
database CRUD operation, i.e., can generate select, insert, update, and delete
commands for us.
 While working with Entity Framework, we can perform different types of
operations on the domain objects (basically classes representing database
tables) using LINQ to entities.
 Entity Framework will generate and execute the SQL command in the database
and then store the results in the instances of your domain objects so that you can
do different types of operations on the data.

Prerequisites to Learn Entity Framework:


To fully benefit from this Entity Framework Course, you should have a basic
understanding of C# as well as any database such as SQL Server, Oracle, or MySQL. It is
recommended that you install the.NET Framework, Visual Studio, and SQL Server on
your computer.

Advantages of Entity Framework:


Maintainability:
Since you have fewer lines of code to fetch data from the database, the fewer lines of code
you have to maintain.
Performance:
The complexity of ORM introduces an obvious slowdown in performance. In the entity
framework first request to fetch data is a little bit slow but after that is fast to fetch data
from the database.
Productivity:
Entity Framework can take up to 35 percent of the entire application code. It makes the
developer’s life easier than ever. Despite its limitations, the designer integrated into Visual
Studio dramatically simplifies the mapping process.
Transactions:
ORM does all possible automation as transactions while querying the data or storing the
data periodically. We can also customize transaction management practices to make the
most of it out of the entity framework.
Example : Entity Framework using Asp.net

Create a new Web forms Asp.net Application

Create a Database TestDB with StudentDetails table with below script,

CREATE TABLE [dbo].[StudentDetails] (


[Id] INT IDENTITY (1, 1) NOT NULL,
[StudentName] VARCHAR (50) NULL,
[Age] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

Add the connection string in Web.config.

<connectionStrings>
<add name="TestConnection" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=TestDB;Integrated
Security=true" />
</connectionStrings>
Create a Class file StudentDetails.cs with below entities and Data context

public class UsersContext : DbContext


{
public UsersContext()
: base("TestConnection")
{
}

public DbSet<StudentDetails> studentDbset { get; set; }


}

public class StudentDetails


{
public int Id { get; set; }
public string StudentName { get; set; }
public int? Age { get; set; }
}

Create AddStudent.Aspx file with the below snippet in Form tag.

<div>
<table border="0" cellspacing="2" cellpadding="2" style="padding:5px">
<tr>
<td colspan="2">Add Student Details
</td>
</tr>
<tr>
<td>Student Name
</td>
<td>
<asp:TextBox ID="txtStudentName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Age
</td>
<td>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save"
OnClick="btnSave_Click" />
<asp:Button ID="btnUpdate" runat="server" Text="Update"
OnClick="btnUpdate_Click" />
<asp:HiddenField ID="hfId" runat="server" />
</td>
</tr>
</table>
<table border="0" cellspacing="2" cellpadding="2">
<tr>
<<td colspan="3">
<asp:GridView ID="grvStudentDetails" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Id" DataField="Id" />
<asp:BoundField HeaderText="Student Name"
DataField="StudentName" />
<asp:BoundField HeaderText="Age" DataField="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit"
OnClick="btnEdit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>

Below Code snippet in AddStudent.aspx.cs file

UsersContext objUsersContext = new UsersContext();


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<StudentDetails> objStudentDetails =
objUsersContext.studentDbset.ToList();
grvStudentDetails.DataSource = objStudentDetails;
grvStudentDetails.DataBind();
btnUpdate.Visible = false;
}
}

protected void btnSave_Click(object sender, EventArgs e)


{
StudentDetails objStudentDetails = new StudentDetails();
objStudentDetails.StudentName = txtStudentName.Text;
objStudentDetails.Age = Convert.ToInt32(txtAge.Text);
objUsersContext.studentDbset.Add(objStudentDetails);
objUsersContext.SaveChanges();
Response.Write("Added Successfully");
}

protected void btnEdit_Click(object sender, EventArgs e)


{
Button btn = (Button)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
if (row != null)
{
int index = row.RowIndex; //gets the row index selected
txtStudentName.Text = row.Cells[1].Text;
txtAge.Text = row.Cells[2].Text;
hfId.Value = row.Cells[0].Text;

}
btnSave.Visible = false;
btnUpdate.Visible = true;
}

protected void btnUpdate_Click(object sender, EventArgs e)


{
int id = Convert.ToInt32(hfId.Value);
StudentDetails objStudentDetails = objUsersContext.studentDbset.Find(id);
objStudentDetails.StudentName = txtStudentName.Text;
objStudentDetails.Age = Convert.ToInt32(txtAge.Text);
objUsersContext.Entry(objStudentDetails).State = EntityState.Modified;
objUsersContext.SaveChanges();
Response.Write("Updated Successfully");
Page_Load(null, null);
}

Solution Structure as below,

You might also like