2013-08-29 74 views
3

我在使用EF5應用一些代碼來軟刪除記錄。我的「deletable」類實現了ISoftDelete,它只是說實現者必須具有一個bool Deleted屬性。「軟刪除」在實體框架5

當我的用戶點擊刪除我打電話DbContext..Remove(實體)

這將清除綁定到父實體爲null的任何屬性(如果我父母有我刪除的實體的集合!)。

在我的DbContext中,我重寫了SaveChanges方法來查找任何已刪除的實體,如果它們實現了我的ISoftDelete接口,我將狀態設置爲已修改而不是已刪除,並將其Deleted屬性設置爲true以標記爲已刪除。我的問題是,持有父項引用的屬性爲空。

調查似乎指向ApplyOriginalValues,但由於我的值不是公共屬性,而是因爲作爲集合中的孩子而創建的,所以我正在努力實現。你能幫我嗎?

回答

2

我覺得如果你使用另一種方法可能會更容易。 使用存儲庫和Unit of Work fascade模式而不是直接調用EF Context,意味着您可以更輕鬆地控制操作。 工作單位類控制savechanges操作。 存儲庫類控制CRUD,GetLists等。

public class RepositoryBase<TPoco> : IRespository { 

     public RepositoryBase(DbContext context) { Context = context; } 
      //... CRUD methods.... 
      public bool Remove(TPoco poco) { 
        if (typeof ISoftDelete).IsAssignableFrom(Typeof(TPoco)){ 
         // proceed with modify actions 
        } 
        else { 
          Context.Set<TPoco>().Remove(poco); 
        } 
      } 
    } 

    public class Luw : ILuw{ 
     // .... 
      public IRepositoryBase<TPoco> GetRepository<TPoco>() where TPoco : ???{ 
       return (new RepositoryFactory<TPoco>().GetRepository(Context)); 
     } 

    public MuCustomResult Commit() { 
      .... any special context manipulation before save 
      myCustomResultRecordsAffected = Context.SaveChanges(); 

    } 
} 
+0

我認爲你可能是對的Phil。不知道要付出多少努力,但絕對是正確的做法。歡呼的建議,會去互聯網尋找一個很好的簡單的EF知識庫例子/教程。 – CheGuevarasBeret

+0

如果您有權訪問pluralsight我知道有一些很好的例子。但加入需要花費。 –