Insert & update records by single method using entity framework
In this blog post we are going to share a trick where you can insert & update records using a single method. So let's discuss about this method.
DataBase Table Name :UserDetail
Table Design:
Step 1 - Add new ADO.NET Entity Model(edmx) & include UserDetail table in Model.
Step 2- Create a new method name CreateUpdateUser . Here I pass the UserDetail Object as a parameter & method will return new Created UserId or Edited UserId .
DataBase Table Name :UserDetail
Table Design:
Column Name | Data Type |
UserId | int(primary key) |
UserName | nvarchar(max) |
FirstName | nvarchar(max) |
LastName | nvarchar(max) |
nvarchar(max) |
Step 2- Create a new method name CreateUpdateUser . Here I pass the UserDetail Object as a parameter & method will return new Created UserId or Edited UserId .
public int CreateUpdateUser(UserDetail ud)
{
int UserId = 0;
using (DBEntities db = new DBEntities())
{
if (ud.UserId > 0)
{
UserDetail temp = db.UserDetails.Where(u => u.UserId == ud.UserId).FirstOrDefault();
if (temp != null)
{
temp.Username = ud.Username;
temp.Firstname = ud.Firstname;
temp.Lastname = ud.Lastname;
temp.Email = ud.Email;
}
}
else
{
db.UserDetails.AddObject(ud);
}
int x = db.SaveChanges();
if (x > 0)
{
UserId = ud.UserId;
}
}
return UserId;
}
Insert User Example
UserDetail ob = new UserDetail();
ob.UserId=0;
ob.UserName = "Shivam";
ob.FirstName = "Shivam";
ob.LastName="Srivastava";
ob.Email ="xyz@abc.com";
int x=CreateUpdateUser(ob);
if(x>0)
{
MessageBox.Show("New User Created");
}
Edit User Example
UserDetail ob = new UserDetail();
ob.UserId=1;
ob.UserName = "Shivam";
ob.FirstName = "Shivam";
ob.LastName="Srivastava";
ob.Email ="pqr@abc.com";
int x=CreateUpdateUser(ob);
if(x>0)
{
MessageBox.Show("User is Updated");
}
In Entity Framework 5 or higher use
ReplyDeletedb.UserDetails.Add(ud);
Nice article Its working thanks!!!!!!