I'm new to Entity Framework. I'm trying to update a record and save changes to the database.
public void SaveEdit(Gate gate)
{
try
{
using (dc = new GateEntities())
{
var query = (from tbsite in dc.tblSites
where tbsite.ID == gate.ID
select tbsite).FirstOrDefault();
query.CalledInAt = gate.CalledInAt;
query.CallerRequest = gate.CallerRequest;
query.ContactPersonOnSite = gate.ContactPersonOnSite;
query.Email = gate.Email;
query.EmailSitePerson = gate.EmailSitePerson;
dc.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}
It gets no exceptions or error messages but it does not save the changes to the database. why it's not updating the record?
We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.
Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.
Right-click anywhere on the design surface, and select Update Model from Database... In the Update Wizard, select the Refresh tab and select your table then click Finish button.
After You modify query
object You should change it's state to Modified
before calling context.SaveChanges()
. Your context object should know about the entity that You modify. Assuming dc
is Your context object:
query.CalledInAt = gate.CalledInAt;
//change other properties ..
dc.Entry(query).State = EntityState.Modified;
dc.SaveChanges();
That should work for You.
You have to use the entityframework to select your object, with that the result object will be track-able, so try this
using (var dc = new GateEntities())
{
var gate = dc.tblSites.Where(g => g.ID == date.ID).FirstOrDefault();
gate.CalledInAt = gate.CalledInAt;
gate.CallerRequest = gate.CallerRequest;
gate.ContactPersonOnSite = gate.ContactPersonOnSite;
gate.Email = gate.Email;
gate.EmailSitePerson = gate.EmailSitePerson;
dc.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With