Every .NET developer sometime will start using ADO.NET Entity Framework.
And first question will be such as how to insert, update and delete records.
Performing basic Inser, Update and Delete operations via the Entity Framework is very straight forward.
first you need to create a Database Table -
Script-
Create Database StudentDetail
USE [StudentDetail]
GO
CREATE TABLE [dbo].[login](
[loginid] [varchar](20) NOT NULL,
[password] [varchar](20) NOT NULL,
[rights] [varchar](20) Null
)
after that you need to create a new Project windows or Web as per your Knowledge and Need..
Right Click on Project in SolutionExplorer Add -> Add New Item .opens a Pop Window , Add new edmx File like this.
Rename the file Name Click Add. it opens a new Popup Window Data Model Wizard. select Generate From Database click on Next Button . Click on New Connection Button , Connection Properties Popup Opens. Change Datasource as Microsoft SQL Server. Provide Server Name, Database name and Click OK button.
Entity Class name is byDefault Entered in TextBox like Below , Click on Next.
in the Next Popup Select Table from Database Click on Finish Button. Your edmx file Looks like This
Now you have to Write the Code for CRUD operation...
for insert Operation use the below Code in Your Function
using (StudentDetailEntities std = new StudentDetailEntities())
{
#region Code for insert row in Table using EF
login
log = new login()
{ loginid = "S009", password = "pass", rights = "user" };
//Add
to memory
std.AddTologins(log);
//Save
to database
std.SaveChanges();
#endregion
}
using (StudentDetailEntities std = new StudentDetailEntities())
{
#region Code for Update row in Table using EF
//Get
the specific LoginID from Database
login
_log = (from log in
std.logins where log.loginid == "S009" select log).First();
//Change
the LoginID in memory
_log.password = "s009";
//Save
to database
std.SaveChanges();
#endregion
}
for Delete Operation use the below Code in Your Function
using (StudentDetailEntities std = new StudentDetailEntities())
{
#region Code for Delete row in Table using EF
login
_login= (from log in
std.logins where log.loginid== "s009" select
log).First();
std.DeleteObject(_login);
std.SaveChanges();
#endregion
}
Happy coding!
Thanks and Regards
SUraj K Mad.
Good Keep It UP!!!
ReplyDeleteThanks sir :)
DeleteAnother generic way of updating using EF could be like given below :-
ReplyDelete[HttpPost]
public ActionResult Edit(Login _login)
{
using (StudentDetailEntities std = new StudentDetailEntities())
{
std.Logins.AddObject(_login);
std.ObjectStateManager.ChangeObjectState(_login,System.Data.EntityState.Modified);
//Save to database
std.SaveChanges();
}
}
replace "_login,System.Data.EntityState.Modified" with _login,System.Data.EntityState.Added
Delete