2017-06-28 30 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();