After we use the ADO. Data model to generate the entity class, the general will make basic additions and deletions to these classes, if each class to write these basic methods, it is too boring. The following is a step by step approach to how to use DbContext to achieve general additions and deletions to the rest of the method, and the implementation of the problem is easy to appear in the process.
1. Open vs2012 and create a new class library project
2. Add a new ADO Data model entry to this project
3. Open App. Config and modify res://* to Res://yourproject
Otherwise the following error will be reported:
WIFI.SSDL (3,4): Error 0019:each type name in a schema must is unique. Type name ' WifiModel.Store.AD ' was already defined.
4. Build this project
5. Create a project for another Web API
ASP. NET MVC 4 Web application–> Web API template
Note that the EF version of this project is consistent with the version of the previous project
6. Add a class to models:
Public classGenericdbcontext<t>: WifientitieswhereT:class { PublicDbset<t> Items {Get;Set; } PublicList<t>Get () {returnSet<t>(). ToList (); } PublicT Get (intID) {returnItems.Find (ID); } Public voidPut (T Item) {Items.attach (item); Entry (item). State=entitystate.modified; SaveChanges (); } Public voidPost (T Item) {Items.Add (item); SaveChanges (); } Public voidDelete (intID) {Delete (Get (id)); } Public voidDelete (T Item) {Items.attach (item); Entry (item). State=entitystate.deleted; SaveChanges (); } }
7. Add one to controllers below:
Public classGenericcontroller<t>: ApicontrollerwhereT:class { Private ReadOnlygenericdbcontext<t> _context =NewGenericdbcontext<t>(); PublicList<t>Get () {return_context. Get (); } PublicT Get (intID) {return_context. Get (ID); } Public voidPost ([frombody]t T) {_context. Post (t); } Public voidPut ([frombody]t T) {_context. Put (t); } Public voidDelete (intID) {_context. Delete (ID); } }
At this point, the general method has been finished
8. You can write a specific controller below.
public class Adcontroller:genericcontroller<ad>
{
}
...
9. Finally debugging with the SOAP UI,