Asp.net
如何將實體框架與 Web API 混合使用
我正在研究新的 ASP.NET MVC4 Web API 框架。我在 Windows 8 消費者預覽版上執行 Visual Studio 2011 beta。
我的問題是新的 Web API 框架的官方範例都沒有使用任何類型的數據庫後端。過去,我能夠創建一個本地 SQL CE 數據庫,並通過使用實體框架作為 ORM 的 WCF 數據服務為其提供服務。我如何對 Web API 做同樣的事情?
另外,這甚至是一個有效的問題嗎?如果我想公開實體框架映射的 SQL CE 數據庫,是否應該繼續使用 WCF 數據服務?它似乎工作正常,除了不提供選擇我可能通過 web api 獲得的響應格式化程序的靈活性。
如果您查看官方的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); } }但是,您的里程可能會有所不同,並且您可能希望進一步抽像出其中一些數據訪問。好消息是,您可能已經在基於 MVC 的項目中使用的大量模式和想法仍然有效。