Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix Entity Framework with Web API

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.

like image 548
Jeremy Bell Avatar asked Mar 05 '12 21:03

Jeremy Bell


People also ask

How do I add Entity Framework to 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.

Which .NET framework supports web API?

8) Which . NET framework supports Web API? NET 4.0 and above version supports web API.

Is Entity Framework an 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.


1 Answers

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.

like image 61
JSancho Avatar answered Sep 28 '22 13:09

JSancho