Thursday, February 2, 2012

How to update a record through EntityFramework in C#?

To update record with the help of EF we use this code
public void Update(tblAdmin objtblAdmin)
{
try
{
using (MyMotorEntities objDb = new MyMotorEntities())

{
var objAdmin = (from t in objDb.tblAdmins.Where(p => p.IdAdmins == objtblAdmin.IdAdmins) select t).FirstOrDefault();
if (objAdmin.IdAdmins > 0)
{objAdmin.Email = objtblAdmin.Email;
objAdmin.Firstname = objtblAdmin.Firstname;
objDb.SaveChanges();

}

}

ReportSuccess();

}
catch (Exception ex)
{
ReportError(ex);
}
}

But what happens when the tblAdmin has lots of fields :) ok don't worry we can use Attach for this.Attach allows us to attach to a record within the context, perform a straight replace on the record with the new modified record and save back the changes and All just within just 3 lines of codes... lolz :)

Here is this ...

public void Update(tblAdmin objtblAdmin)

{
try
{

using (MyMotorEntities objDb = new MyMotorEntities())
{
objDb.tblAdmins.Attach(objDb.tblAdmins.Single(c => c.IdAdmins == objtblAdmin.IdAdmins));
objDb.tblAdmins.ApplyCurrentValues(objtblAdmin);
objDb.SaveChanges();
}

ReportSuccess();
}
catch (Exception ex)
{
ReportError(ex);
}
}

Cheers :)