How to mix Entity Framework with Web API

后端 未结 2 453
-上瘾入骨i
-上瘾入骨i 2021-02-09 03:30

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

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-09 04:10

    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 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 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.

提交回复
热议问题