Mvc缓存禁用对象更改跟踪

时间:2017-06-28 20:15:16

标签: c# asp.net-mvc caching change-tracking

我在我的mvc 5网站上使用缓存,
我在缓存中有一个对象 当我得到这个对象时,我们可以从缓存中调用它并将其复制到另一个对象,然后将其称为object2 我在object2上执行的每个更改都会自动反映到object1和缓存的对象
现在,当我再次从缓存中获取对象时,它将模拟我对objec2所做的更改,因为更改跟踪,我不需要 我怎样才能避免重新选择缓存的更改

这是我的代码

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; }
}

1 个答案:

答案 0 :(得分: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();