We use ADO. after NET Entity Data Model is used to generate Entity classes, basic addition, deletion, modification, and query operations are generally performed on these classes. It is too boring to write these basic methods for each class. The following describes how to use DBContext to implement the general addition, deletion, modification, and query REST methods through step by step, as well as problems that may occur during implementation.
1. Open vs2012 and create a class library project.
2. Add an ADO. NET Entity Data Model item to this project.
3. Open App. Config and modify res: // * to res: // yourproject
Otherwise, the following error will be reported:
WIFI. ssdl (0019): error: Each type name in a schema must be unique. Type name 'wifimodel. Store. ad' was already defined.
4. Build this project
5. Create another web api Project
ASP. net mvc 4 Web Application-> Web API Template
Note that the EF version of this project must be consistent with that of the previous project.
6. Add a class to Models:
public class GenericDBContext<T> : WifiEntities where T : class { public DbSet<T> Items { get; set; } public List<T> Get() { return Set<T>().ToList(); } public T Get(int id) { return Items.Find(id); } public void Put(T item) { Items.Attach(item); Entry(item).State = EntityState.Modified; SaveChanges(); } public void Post(T item) { Items.Add(item); SaveChanges(); } public void Delete(int id) { Delete(Get(id)); } public void Delete(T item) { Items.Attach(item); Entry(item).State = EntityState.Deleted; SaveChanges(); } }
7. Add one to Controllers:
public class GenericController<T> : ApiController where T : class { private readonly GenericDBContext<T> _context = new GenericDBContext<T>(); public List<T> Get() { return _context.Get(); } public T Get(int id) { return _context.Get(id); } public void Post([FromBody]T t) { _context.Post(t); } public void Put([FromBody]T t) { _context.Put(t); } public void Delete(int id) { _context.Delete(id); } }
Now, the general method has been written.
8. The specific Controller can be written below.
Public class ADController: GenericController <AD>
{
}
...
9. Finally, use the soap ui for debugging.