Search code examples
c#asp.netentity-framework-6asp.net-4.5entitydatasource

Microsoft.AspNet.EntityDataSource gives wrong entity's property value during Updating or Deleting


I am using the Microsoft.AspNet.EntityDataSource like this:

ASPX:

<asp:GridView runat="server" DataSourceID="eds" ID="gv" AutoGenerateColumns="false" DataKeyNames="ID">
  <Columns>
    <asp:BoundField DataField="ID" HeaderText="#" ReadOnly="true" />
    <asp:BoundField DataField="Name" HeaderText="Name" />
    <asp:BoundField DataField="Code" HeaderText="Code" ReadOnly="true" />
    <asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true" />
  </Columns>
</asp:GridView>

<ef:EntityDataSource runat="server" ID="eds" ConnectionString="name=Entities" 
                     EnableDelete="true" EnableInsert="True" EnableUpdate="True"
                     EntitySetName="awCategoryGroups" DefaultContainerName="Entities" EnableFlattening="False"
                     Where="it.isValid=true"  OrderBy="it.Name asc" OnDeleting="eds_Deleting">
</ef:EntityDataSource>

It creates a table with records (entities) of type awCategoryGroup. The problem is, when I want to delete the record using the delete button from GridView CommandField whic calls the eds_Deleting method.

C#:

protected void eds_Deleting(object sender, Microsoft.AspNet.EntityDataSource.EntityDataSourceChangingEventArgs e)
{
    awCategoryGroup cg = (awCategoryGroup)e.Entity;
    cg.isValid = false;
    e.Context.SaveChanges();
    e.Cancel = true;
}

The database looks like this when selecting data for GridView.

DB:

ID  Name    Code    isValid
==========================================
19  Roles   UserRole    True
20  Actions ActionType  True

The goal should be to set isValid column to False. But when eds_Deleting method is called, the (awCategoryGroup)e.Entity contains corresponding values of its properties except the bool (in DB as bit) valued property isValid. It should be True, but it is False already before I set it. So no save occures when calling e.Context.SaveChanges();, because the properties are not modified.

Is it a bug or am I doing something wrong? This philosophy worked fine on EF4, but after migrating to EF6, there is the problem.


Solution

  • It looks like the isValid must be as one of the visible columns in the GridView.

    So eds_Deleting exactly do not work with the entity from database but only with its part used in GridView. Values not used in GridView are of default value (usually null or false).

    So this is inter alia the difference between EF5 EntityDataSource and EF6 EntityDataSource. EF5 version worked with the fully loaded object, but EF6 do not.