How to cache asp.net mvc data using Cache obect

I am using data caching in my asp.net application. This is my frontend for ICacheProvider.cs

public interface ICacheProvider
{
    object Get(string key);
    void Set(string key, object data, int cacheTime);
    bool IsSet(string key);
    void Invalidate(string key);
}

      

This is how I use caching in services.

public List<EmployeeLookUp> GetEmployeeLookUp(RecordStatusEnum recordStatusEnum, int locatioId)
    {
        var status = (int)recordStatusEnum;

        var employeeData = Cache.Get("EmployeeLookUp") as IEnumerable;

        if (employeeData == null)
        {
            var result = MyDb.Employee.Where(w => w.Status == status && w.LocationId == locatioId).ToList().Select(s => new EmployeeLookUp()
            {
                EmployeeId = s.EmployeeId,
                DepartmentId = s.DepartmentId,
                EmployeeValue = string.Format("{0}{1}{2} {3} {4}", "[", s.CustomEmployeeId, "]", s.FirstName, s.LastName)
            }).ToList();

            if (result.Any())
                Cache.Set("EmployeeLookUp", result, 30);

            return result;
        }

        return (List<EmployeeLookUp>) employeeData;
    }

      

In the controller, I am using the returned employees like this.

 public ActionResult Index()
    {
        var employees = _employeeServices.GetEmployeeLookUp(RecordStatusEnum.Active, User.GetCemexUser().LocationId);
        employees.Insert(0, new EmployeeLookUp() { EmployeeId = -1, EmployeeValue = "All" });

        var complexRosterViewModel = new ComplexRosterViewModel
        {
            EmployeeList = new SelectList(employees, "EmployeeId", "EmployeeValue"),
            ListEmployeeGroups = new SelectList(_employeeGroupServices.GetEmployeeGroup(RecordStatusEnum.Active, User.GetCemexUser().LocationId), "EmployeeGroupId", "Value"),
            ListDepartments = new SelectList(_departmentService.GetDepartments(RecordStatusEnum.Active,User.GetCemexUser().LocationId),"DepartmentId","Value")
        };

        return View(complexRosterViewModel);
    }

      

Now my problem is that when I reload the page multiple times, the extra "Everyone" option I added to the employee picklist was added to the cached object ("EmployeeLookUp") multiple times. How is this possible? I do not want the "All" option to be cached.

+3


source to share


1 answer


This is because you are using a reference to a cached object. If you change the object, it will reflect the changes to the cached data.

Asp.Net Cache, change object from cache and change cached value



You have to clone an object or create a new one and copy property values ​​(you can use AutoMapper for this)

Hope it helps.

+1


source







All Articles