0

这是我的代码:

 public void  DeleteFolder(Entities.DocumentFolder folder)
    {
         DeleteFilesFromServer(folder.Id);
        _dbContext.Entry(folder).State = EntityState.Deleted;
        _dbContext.SaveChanges();          
    }

   public void  DeleteFilesFromServer(int id)
   {
       var allDocuments = _dbContext.Document.Where(x => x.FolderId == id).ToList();
       foreach (var filePath in allDocuments.Select(document => HttpContext.Current.Server.MapPath("~/Documents/") + document.DocumentFileName).Where(System.IO.File.Exists))
       {
           System.IO.File.Delete(filePath);
       }
   }


 public class DocumentFolder
    {
      public DocumentFolder()
      {
          Documents=new List<Document>();
      }
      public int Id { get; set; }
      public string FolderName { get; set; }
      public int ParentFolderId { get; set; }
      public List<Document> Documents { get; set; }
    }
  public class Document
  {
      public int Id { get; set; }
      public string DocumentName { get; set; }
      public string DocumentFileName { get; set; }
      public int FolderId { get; set; }
      public virtual DocumentFolder Folder { get; set; }
  }

通过执行删除操作,我得到了以下异常:

System.InvalidOperationException:操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

如果我删除DeleteFilesFromServer(int id)该删除工作的方法。有人能帮我吗?

4

1 回答 1

0

If you want to delete the DocumentFolder, you need to delete the Document objects related to the DocumentFolder because in your model the field Folder is not nullable. This happens only if the dbContext knows that the the Document objects exist, i.e. if you load the documents with the Select method.

于 2012-08-16T10:23:10.503 回答