如何同时删除文件夹中的所有相关文件和数据库中的引用?

How do I delete all related files in file folder and the references in my database at the same time?

我的应用程序具有引用相应 SQL 表的支持模型。一个 SBanInfos 拥有有关用户的所有数据。另一个 SBanFileDetails 全部存储与 guid 匹配的文件的 guid,以及文件本身的源。

在编辑模式下,我可以像这样同时从文件夹和 SBanFileDetails 中单独删除文件:

[HttpPost]
public JsonResult DeleteFile(string id)
{
    if (String.IsNullOrEmpty(id))
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { Result = "Error" });
    }
    try
    {
        Guid guid = new Guid(id);
        SBanFileDetail sBanFileDetail = db.SBanFileDetails.Find(guid);
        if (sBanFileDetail == null)
        {
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return Json(new { Result = "Error" });
        }

        //Remove from database
        db.SBanFileDetails.Remove(sBanFileDetail);
        db.SaveChanges();
        //Delete file from the file system
        var path = Path.Combine(Server.MapPath("~/pathto/myfile/"), sBanFileDetail.Id + sBanFileDetail.Extension);
        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }
        return Json(new { Result = "OK" });
    }
    catch (Exception ex)
    {
        return Json(new { Result = "ERROR", Message = ex.Message });
    }
}

我从经验中知道我可以像这样删除与用户和用户记录相关的所有 SBanFileDetails

SBanInfo sBanInfo = db.SBanInfos.Find(id);
    db.SBanFileDetails
       .Where(p => p.SubjectId == id)
       .ToList()
       .ForEach(p => db.SBanFileDetails.Remove(p));
    db.SBanInfos.Remove(sBanInfo);
    db.SaveChanges();

我的问题是,如何同时删除数据库中的引用和文件夹中的文件?

按照 Andrei 的建议,我按照正确的顺序放置了上面的所有部分以解决问题。最终代码如下所示

var subjectIdResult = (from sId in db.SBanInfos where sId.SubjectId == id select sId.SubjectId).Single();
var fileDetailsResult = (from fd in db.SBanFileDetails where fd.SubjectId == subjectIdResult select fd.Id).ToList();

foreach(var fileId in fileDetailsResult)
{ 
    Guid guid = new Guid(fileId.ToByteArray());
    SBanFileDetail sBanFileDetail = db.SBanFileDetails.Find(guid);

    //Delete files from the file system
    var path = Path.Combine(Server.MapPath("~/pathto/myfiles/"), sBanFileDetail.Id + sBanFileDetail.Extension);
    if (System.IO.File.Exists(path))
    {
        System.IO.File.Delete(path);
    }
}

SBanInfo sBanInfo = db.SBanInfos.Find(id);
db.SBanFileDetails
   .Where(p => p.SubjectId == id)
   .ToList()
   .ForEach(p => db.SBanFileDetails.Remove(p));
db.SBanInfos.Remove(sBanInfo);
db.SaveChanges();
return RedirectToAction("Index");