Search code examples
c#asp.netentity-frameworkgridviewentitydatasource

Null values in entity when entitydatasource Deleting Event raised


I'm currently using the Entity Framework and I have a Gridview displaying a list of records from a database. I have a Remove button the uses the Delete command. Each record has a file on the server associated with it, so when the data source raises the deleting event I want to grab the filename and delete the file from the server as well. The weird thing is that in my ds_Deleting event some of the values in the entity are null. I can't seem to figure out why.

The code for my Delete button in the gridview is the following:

<asp:TemplateField HeaderText="Remove">
    <ItemTemplate>
        <asp:Button ID="btnRemove" runat="server" Text="Remove" CssClass="button_default" CommandName="Delete" OnClientClick="return confirm('Deleting this contract will also delete the file from the server. Continue?')" />
     </ItemTemplate>
 </asp:TemplateField>

The OnDeleting event in the codebehind looks like this:

protected void dsContracts_Deleting(object sender, EntityDataSourceChangingEventArgs e)
{
    ipiModel.Contract contract = (ipiModel.Contract)e.Entity;

    File.Delete(Path.Combine(ConfigurationManager.AppSettings["ContractUploadPath"], contract.FileName));
}

Every time the contract.FileName value is null, even though it is displayed properly in the GridView. Any help would be much appreciated. Thanks!


Solution

  • I managed to figure this out and decided I'd write it down here in case anyone else has the same problem. I checked the documentation on MSDN for the deleting event of the entity data source (which can be found here) and it said

    The Entity property of the EntityDataSourceChangingEventArgs object is used to access the object to be deleted. The properties of this object may not be fully set. Only the properties required to identify the object must be set.

    So this is why I was getting null values. The solution I came up with probably isn't ideal but it works. I realized the primary key ContractID always had a value so I used it to pull the record from the database. Here is my code:

    protected void dsContracts_Deleting1(object sender, EntityDataSourceChangingEventArgs e)
    {
        ipiModel.Contract ct = (ipiModel.Contract)e.Entity;
    
        using (var db = new ipiModel.ipiEntities())
        {
            var contract = db.Contracts.Where(c => c.ContractID == ct.ContractID).Single();
    
            File.Delete(Path.Combine(ConfigurationManager.AppSettings["ContractUploadPath"], contract.FileName));
        }
    }