如何使用缓存 obect 将数据缓存 asp.net mvc
本文关键字:缓存 asp net 数据 mvc 何使用 obect | 更新日期: 2023-09-27 17:56:24
我在 asp.net 应用程序中使用数据缓存。这是我的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);
}
这是我在服务中使用缓存的方式。
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;
}
在控制器中,我像这样使用员工的返回。
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);
}
现在我的问题是,当我多次重新加载页面时,我添加到员工选择列表中的附加"全部"选项已多次添加到缓存对象("EmployeeLookUp")中。这怎么可能?我不希望缓存"全部"选项。
发生这种情况是因为您正在使用对缓存对象的引用。如果更改对象,它将反映缓存数据中的更改。
Asp.Net 缓存中,修改缓存中的对象,它会更改缓存的值
您必须克隆对象或创建一个新的对象并复制属性值(您可以使用自动映射器为您执行此操作)
希望对您有所帮助。