WebApi与数据库连接的休息Web服务

时间:2013-10-28 03:54:14

标签: mysql rest asp.net-web-api

我使用WebApi创建了一个示例rest webservice。 这是名为Employee Controller的控制器类。

namespace HelloWebApi.Controllers
{
    public class EmployeesController : ApiController
    {
        private static IList<Employee> list = new List<Employee>()
        {
            new Employee()
            {
            Id = 12345, FirstName = "John", LastName = "Human",Department = 2
            },
            new Employee()
            {
            Id = 12346, FirstName = "Jane", LastName = "Public",Department = 3
            },
            new Employee()
            {
            Id = 12347, FirstName = "Joseph", LastName = "Law",Department = 2
            }
        };
 // GET api/employees
        public IEnumerable<Employee> Get()
        {
            return list;
        }

        // GET api/employees/12345
        public Employee Get(int id)
        {
            return list.First(e => e.Id == id);
        }
        // POST api/employees
        public void Post(Employee employee)
        {
            int maxId = list.Max(e => e.Id);
            employee.Id = maxId + 1;
            list.Add(employee);
        }
        // PUT api/employees/12345
        public void Put(int id, Employee employee)
        {
            int index = list.ToList().FindIndex(e => e.Id == id);
            list[index] = employee;
        }
        // DELETE api/employees/12345
        public void Delete(int id)
        {
            Employee employee = Get(id);
            list.Remove(employee);
        }

        public HttpResponseMessage Patch(int id, Delta<Employee> deltaEmployee)
        {
            var employee = list.FirstOrDefault(e => e.Id == id);
            if (employee == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            deltaEmployee.Patch(employee);
            return Request.CreateResponse(HttpStatusCode.NoContent);
        }
    }
}

这里我使用了所有HTTP谓词方法进行插入,更新,删除。我使用了一个存储Employee对象的列表。插入,删除和更新基于此列表。但是这个程序没有数据库连接。我想知道如何在此程序中使用数据库访问。我想使用数据库中的表。我怎么能这样做?请联系任何有用的链接。

0 个答案:

没有答案