这是一个非常模糊/主观的问题。我想知道这是否是使用ajax调用向/从浏览器发送/检索数据的最佳方式。在后端web服务上,我想使用实体框架。以下是两个示例函数。如何改善实体框架和Javascript交互
“最好”的标准是编写代码的速度,可读代码和可靠的体系结构。
感谢您的任何意见和建议和意见。
获取函数
[WebMethod]
public AjaxEmployee EmployeeGetById(int employeeID, bool getTimeOff)
{
using (Time_TrackerEntities ctx = new Time_TrackerEntities())
{
var results = from item in ctx.Employees
where item.ID == employeeID
orderby item.Last_Name
select new AjaxEmployee
{
ID = item.ID,
Employee_ID = item.Employee_ID,
First_Name = item.First_Name,
Middle_Name = item.Middle_Name,
Last_Name = item.Last_Name,
Supervisor_ID = item.Supervisor_ID,
Active = item.Active,
Is_Supervisor = item.Is_Supervisor
};
var emp = results.FirstOrDefault();
if (getTimeOff)
{
var results2 = from item2 in ctx.Time_Off
where item2.Employee_ID == emp.Employee_ID
select new AjaxTime_Off
{
ID = item2.ID,
Employee_ID = item2.Employee_ID,
Date_Off = item2.Date_Off,
Hours = item2.Hours
};
emp.Time_Off = results2.ToList<AjaxTime_Off>();
}
return emp;
}
}
保存功能
[WebMethod]
public bool EmployeeSave(AjaxEmployee emp)
{
using (Time_TrackerEntities ctx = new Time_TrackerEntities())
{
var results = from item in ctx.Employees
where item.ID == emp.ID
select item;
var myEmp = results.FirstOrDefault();
if (myEmp == null)
{
myEmp = new Employee();
ctx.Employees.AddObject(myEmp);
}
myEmp.Employee_ID = emp.Employee_ID;
myEmp.First_Name = emp.First_Name;
myEmp.Middle_Name = emp.Middle_Name;
myEmp.Last_Name = emp.Last_Name;
myEmp.Supervisor_ID = emp.Supervisor_ID;
myEmp.Active = emp.Active;
myEmp.Is_Supervisor = emp.Is_Supervisor;
return ctx.SaveChanges() > 0;
}
}
为什么你有单独的`AjaxEmployee`类?它是你的“员工”实体的投影吗? – 2011-02-14 02:34:12
单独的类,是发送到JavaScript时更好地序列化为JSON。由于Employee和Time_Off记录之间存在关系,所以序列化不会按照以下内容正确执行:http://mytechworld.officeacuity.com/?p=577 – Sam 2011-02-14 15:13:30