本文介绍了如何实体框架使用Web API混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究新的ASP.NET的Web MVC4 API框架。我在Windows 8消费者preVIEW运行Visual Studio 2011测试版。

I'm researching the new ASP.NET MVC4 Web API framework. I'm running Visual Studio 2011 beta on the Windows 8 consumer preview.

我的问题是,没有为新的Web API框架正式样品使用任何一种数据库后端的。在过去,我已经能够创建一个本地SQL CE数据库,并使用实体框架的ORM通过WCF数据服务服务于它。我该怎么做同样的使用Web API?

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?

此外,这是甚至一个有效的问题?我应该继续使用WCF数据服务,如果我要揭露一个实体框架映射SQL CE数据库?它似乎比不提供灵活选择的响应格式化,我可能会与网页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.

推荐答案

如果你看一下官方的<一个href=\"http://$c$c.msdn.microsoft.com/Contact-Manager-Web-API-0e8e373d/source$c$c?fileId=49595&pathId=1482590740\"相对=nofollow>联系人管理器样品,你会发现,存储库模式用于访问数据层。
另外,请记住,在这个特殊的例子还有通过Ninject也就是DI

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.

在我的情况,我可以轻松接入到这一个已经存在的EF模型。

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);
    }
}

您的里程可能会有所不同,虽然,你可能想抽象出一些这方面的数据访问进一步。
好消息是,大量的,你可以在基于MVC的项目已经使用的模式和理念仍然有效。

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.

这篇关于如何实体框架使用Web API混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 13:18