2017-06-28 41 views
0

我在我的mvc 5網站使用緩存,
我有一個緩存中可用的對象。
當我得到這個對象讓我們從緩存中調用它的object1並將其複製到另一個對象讓我們稱之爲object2。
我在object2上執行它的每一個變化,這個變化自動反映到object1和緩存對象
現在,當我從緩存中再次獲取對象時,它將與我對objec2所做的更改保持一致,因爲變化跟蹤, 「T需要一個 如何避免refelect變化緩存Mvc緩存禁用對象更改跟蹤

這裏是我的代碼

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     //a model with 10 adds 
     Model model = new Model() 
     { 
      pageName = "test", 
      ads = new List<Ads>() 
      { 
       new Ads() {id = 1, image = "1" }, 
       new Ads() {id = 2, image = "2" }, 
       new Ads() {id = 3, image = "3" }, 
       new Ads() {id = 4, image = "4" }, 
       new Ads() {id = 5, image = "5" }, 
       new Ads() {id = 6, image = "6" }, 
       new Ads() {id = 7, image = "7" }, 
       new Ads() {id = 8, image = "8" }, 
       new Ads() {id = 9, image = "9" }, 
       new Ads() {id = 10, image = "10" }, 
      }, 
     }; 

     //cache it 
     HttpContext.Cache.Insert("demo", model, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration); 

     //get cached object 
     Model object1 = HttpContext.Cache.Get("demo") as Model; 

     // => 10 items 
     Console.WriteLine(model.ads.Count()); 

     //just get 3 items of that list 
     Model object2 = object1; // disable changes tracking here 
     object2.ads = object2.ads.Take(3).ToList(); 
     //this changes will be reflected to cached object, i need to disable this 


     //get cached object (from cache) again 
     Model newCachedModel = HttpContext.Cache.Get("demo") as Model; 
     Console.WriteLine(newCachedModel.ads.Count());//3 items only 
     //note i have never change the cached object, the changes reflected from modelToReturn (using changes tracking feature in c#) 

     return View(object2); 
    } 
} 
public class Model 
{ 
    public string pageName { get; set; } 
    public List<Ads> ads { get; set; } 
} 
public class Ads 
{ 
    public int id { get; set; } 
    public string image { get; set; } 
} 

回答

0

我有找到一個解決方案
只是使對象的克隆之前做任何更改

public class Model 
    { 
     public string pageName { get; set; } 
     public List<Ads> ads { get; set; } 

     public Model clone() 
     { 
      return (Model)this.MemberwiseClone(); 
     } 
    } 

    //after clone any changes to object2 will not reflect to object1 
    Model object2 = object1.clone();