简体   繁体   English

处理实体框架SaveChanges()异常以进行清理

[英]Handling Entity Framework SaveChanges() exceptions for cleanup

I have a File Repository library which handles the saving of files onto the server. 我有一个文件存储库库,用于处理将文件保存到服务器上。 Along with saving the physical file, a database entry is also recorded . 除了保存物理文件外, 还将记录数据库条目

Below is the insert method. 下面是插入方法。

public DataFile InsertFile(string fileName, byte[] fileBytes)
{
    File.WriteAllBytes(Path.Combine(FileRepPath, fileName), fileBytes);

    DataFile dataFile = NewDataFile(
        fileName,
        fileBytes.Length
    );

    try
    {
        using (MyEntities context = new MyEntities())
        {
            context.DataFiles.Add(dataFile);
            context.SaveChanges();
        }
    }
    catch (Exception)
    {
        File.Delete(Path.Combine(FileRepPath, fileName));
        throw;
    }

    return dataFile;
}

If the database update fails, then I want to delete the file from the server. 如果数据库更新失败,那么我想从服务器删除文件。 I do this by catching ANY exception that occurs from the context operations and delete the file (and rethrowing the error so that it can bubble up). 我通过捕获上下文操作中发生的任何异常并删除文件(然后将错误重新抛出以使其冒泡)来实现。

Is this correct practice? 这是正确的做法吗? Should I be catching more specific exceptions? 我应该捕获更多特定的异常吗?

I suggest you use the TransactionScope object to manage this task for you. 建议您使用TransactionScope对象为您管理此任务。 Every component that implements the IEnlistmentNotification interface can participate in a two-phase commit of the TransactionScope . 实现IEnlistmentNotification接口的每个组件都可以参与TransactionScope的两阶段提交。

The commit will require enlisting the services of MS-DTC but it will ensure all or nothing is saved. 提交将需要征募MS-DTC的服务,但是它将确保保存全部或全部不保存。 MS-DTC is used to co-ordinate the results of transactions across multiple heterogeneous resources. MS-DTC用于协调多个异构资源之间的事务处理结果。

Here are a couple of Microsoft articles: 以下是几篇Microsoft文章:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM