如何将Entity Framework与Web API混合使用

Jer*_*ell 8 asp.net asp.net-mvc entity-framework asp.net-web-api

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

我的问题是,新的Web API框架的官方示例都没有使用任何类型的数据库后端.在过去,我已经能够创建一个本地SQL CE数据库,并使用Entity Framework作为ORM通过WCF数据服务提供服务.如何使用Web API执行相同的操作?

这也是一个有效的问题吗?如果我想暴露实体框架映射的SQL CE数据库,我应该继续使用WCF数据服务吗?它似乎工作正常,除了不提供选择响应格式化程序的灵活性,我可能会得到web api.

JSa*_*cho 4

如果您查看官方的Contact Manager 示例,您会发现存储库模式用于访问数据层。另外,请记住,在这个特定示例中还存在通过 Ninject 的 DI。

就我而言,我可以轻松地将其插入到现有的 EF 模型中。

这是存储库实现的示例

///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);
    }
}
Run Code Online (Sandbox Code Playgroud)

不过,您的情况可能会有所不同,并且您可能希望进一步抽象出一些数据访问。好消息是,您可能已经在基于 MVC 的项目中使用过的大量模式和想法仍然有效

  • 不错,但在这种情况下我不会费心创建存储库。实体框架,尤其是较新的版本,已经在使用存储库模式。除了增加复杂性之外,包装器没有做任何不同的事情。 (3认同)