How to mix Entity Framework with web API

I am learning a new ASP.NET MVC4 web API framework. I am launching a beta version of Visual Studio 2011 to preview Windows 8.

My problem is that not one of the official samples of the new web API structure uses any database backend. Previously, I could create a local SQL CE database and serve it through the WCF data service using the Entity Framework as an ORM. How can I do the same with the web API?

Also, is that even the right question? Should I just use the WCF data service if I want to open an SQL CE database bound to an Entity Framework? It seems to be working fine, except that it does not offer the flexibility to choose the response forms that I can get using the web api.

+8
asp.net-mvc asp.net-web-api entity-framework
source share
2 answers

If you look at the official Sample Contact Manager , you will find that the repository template is used to access the data layer. Also, keep in mind that there is also a DI through Ninject in this particular example.

In my case, I easily connected this to an existing EF model.

Here is an example repository implementation

///MODEL public class SampleRepository : ISampleRepository { public IQueryable<Users> GetAll() { SampleContext db = new SampleContext(); return db.users; } [...] } ///CONTROLLER private readonly ISampleRepository repository; public SampleController(ISampleRepository repository) { this.repository = repository; } //GET /data public class SampleController : ApiController { public IEnumerable<DataDTO> Get() { var result = repository.GetAll(); if (result.Count > 0) { return result; } var response = new HttpResponseMessage(HttpStatusCode.NotFound); response.Content = new StringContent("Unable to find any result to match your query"); throw new HttpResponseException(response); } } 

Perhaps your mileage may change, and you can further ignore some of this data. The good news is that many of the templates and ideas that you may have already used in MVC-based projects remain valid .

+4
source share

I have not worked with the WCF web API, so I can tell you for sure if you can use it the same as with the WCF Web API, but I am sure that you can use EF with the ASP.NET web API. I suggest you take a look at how ASP.NET MVC uses EF , it should be very similar to how you will use it with the ASP.NET Web API.

As with the other question, if you are planning a new development, you should consider using the ASP.NET Web API, as there is an ad on wcf.codeplex.com saying:

WCF Web API is now ASP.NET Web API! ASP.NET Web Interface Released with ASP.NET MVC 4 Beta. WCF web API and WCF support for jQuery content on this site will be removed by the end of 2012.

+2
source share

All Articles