I'm researching the new ASP.NET MVC4 Web API framework. I'm running Visual Studio 2011 beta on the Windows 8 consumer preview.
My problem is that none of the official samples for the new Web API framework use any kind of database backend. In the past, I've been able to create a local SQL CE database and serve it up via a WCF Data Service using Entity Framework as the ORM. How do I do the same with Web API?
Also, is this even a valid question? Should I just keep using a WCF Data Service if I want to expose an Entity Framework mapped SQL CE database? It seems to work fine, other than not offering the flexibility to choose response formatters that I might get with web api.
In the New Project dialog, select Web in the left pane and ASP.NET Web Application (. NET Framework) in the middle pane. Name the project BookService and select OK. In the New ASP.NET Project dialog, select the Web API template.
8) Which . NET framework supports Web API? NET 4.0 and above version supports web API.
Entity Framework API (EF6 & EF Core) includes the ability to map domain (entity) classes to the database schema, translate & execute LINQ queries to SQL, track changes occurred on entities during their lifetime, and save changes to the database.
If you look at the official Contact Manager sample, you'll find that the Repository Pattern is used to access the data layer. Also, bear in mind that in this particular example there's also DI via Ninject.
In my case I've easily plugged this onto an already existing EF model.
Here's an example for a 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);
}
}
Your mileage may vary though, and you might want to abstract out some of this data access even further. Good news is that plenty of patterns and ideas that you may have already used on MVC-based projects are still valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With