Skip to main content
 首页 » 编程设计

c#之引发实体数据源删除事件时实体中的空值

2024年02月23日15jirigala

我目前正在使用 Entity Framework 并且我有一个 Gridview 显示来自数据库的记录列表。我有一个使用删除命令的删除按钮。每条记录在服务器上都有一个与之关联的文件,因此当数据源引发删除事件时,我想获取文件名并从服务器中删除该文件。奇怪的是,在我的 ds_Deleting 事件中,实体中的某些值是空的。我似乎无法弄清楚为什么。

gridview 中删除按钮的代码如下:

<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> 

代码隐藏中的 OnDeleting 事件如下所示:

protected void dsContracts_Deleting(object sender, EntityDataSourceChangingEventArgs e) 
{ 
    ipiModel.Contract contract = (ipiModel.Contract)e.Entity; 
 
    File.Delete(Path.Combine(ConfigurationManager.AppSettings["ContractUploadPath"], contract.FileName)); 
} 

每次 contract.FileName 值为 null,即使它在 GridView 中正确显示。任何帮助将非常感激。谢谢!

请您参考如下方法:

我设法解决了这个问题,并决定把它写在这里,以防其他人遇到同样的问题。我查看了 MSDN 上的文档以了解实体数据源的删除事件(可以找到 here ),它说

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.

所以这就是我得到空值的原因。我想出的解决方案可能并不理想,但它确实有效。我意识到主键 ContractID 总是有一个值,所以我用它从数据库中提取记录。这是我的代码:

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)); 
    } 
}