Dimuthu Ranmal
Dimuthu Ranmal

Reputation: 55

How to cache data asp.net mvc using Cache obect

I am using data caching in my asp.net application. This is my interface for the 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 the way I'm using caching in the 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'm using the returned of 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, when i'm reloading the page several times, the additional "All" option that I added additionally to the employee select list, has been added to cached object("EmployeeLookUp") several times. How this can be possible? I do not want the "All" option to be cached.

Upvotes: 3

Views: 2273

Answers (1)

Ricardo Pontual
Ricardo Pontual

Reputation: 3757

It happens because you're using a reference to cached object. If you change the object, it will reflect the changes in cached data.

Asp.Net Cache, modify an object from cache and it changes the cached value

You must clone the object or create a new and copy the properties values (you can use AutoMapper to do it for you)

Hope it helps.

Upvotes: 1

Related Questions