Ken Carter Ken Carter - 2 months ago 9
ASP.NET (C#) Question

Doing something wrong with my Entity Update.Code

I have a GridView with a select button that triggers this code. The intent of it is to provide a last minute means to reverse a authorization. Therefore what it is attempting to do I is open a table in the database, updated three columns setting two to null (no absolutely necessary could be blank or left alone for that matter) but the crucial one to change is 'Approved' which needs to be changed to False. I'm red lining of all of my value assignments and my 'SaveChanges()'. I'm very new to coding in c# so I could use some direction here but what I have done here follows what examples I have found and I'm thinking it should be working ... BUT...

Thoughts?

protected void PrePushUpdatesGrd_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = PrePushUpdatesGrd.SelectedRow;
int trackingID = int.Parse(row.Cells[1].Text);

using (CInTracDBEntities1 Context = new CInTracDBEntities1())
{
var UpdateSet = Context.Updates.Where(a => a.CAssetID == trackingID).Select(x => new { x.CAssetID, x.SubmitBy, x.SubmitDT, x.ApproveBy, x.Approved, x.ApprovedDT }).FirstOrDefault();
UpdateSet.ApproveBy = null;
UpdateSet.ApprovedDT = null;
UpdateSet.Approved = "False";

trackingID.SaveChanges();
}

PrePushUpdatesGrd.DataBind();
}

Answer

Try this

protected void PrePushUpdatesGrd_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = PrePushUpdatesGrd.SelectedRow;
    int trackingID = int.Parse(row.Cells[1].Text);

    using (CInTracDBEntities1 Context = new CInTracDBEntities1())
        {
            var UpdateSet = Context.Updates.FirstOrDefault(a => a.CAssetID == trackingID);
                UpdateSet.ApproveBy = null;
                UpdateSet.ApprovedDT = null;
                UpdateSet.Approved = "False";
                Context.Entry(UpdateSet).State= EntityState.Modified; //correct
                Context.SaveChanges();

        }

    PrePushUpdatesGrd.DataBind();            
}
Comments