9-3. 找出Web API中發生了什麼變化問題想通過基於REST的Web API服務對資料庫進行插入,刪除和修改對象圖,而不必為每個實體類編寫單獨的更新方法. 此外, 用EF6的Code Frist實現數據訪問管理.本例,我們模擬一個N層場景,用單獨的客戶端(控制台應用)來調用單獨的基於REST服...
9-3. 找出Web API中發生了什麼變化
問題
想通過基於REST的Web API服務對資料庫進行插入,刪除和修改對象圖,而不必為每個實體類編寫單獨的更新方法. 此外, 用EF6的Code Frist實現數據訪問管理.
本例,我們模擬一個N層場景,用單獨的客戶端(控制台應用)來調用單獨的基於REST服務的Web網站(WEB API應用)
. 註意:每層使用單獨的Visual Studio 解決方案, 這樣更方便配置、調試和模擬一個N層應用。
假設有一個如Figure 9-3所示的旅行社和預訂的模型.
Figure 9-3. 一個旅行社和預訂的模型
模型展示了旅行社和他們的預訂之間的關係. 我們要把模型和資料庫訪問放到WEB API服務後面,這樣任何客戶端都可以通過HTTP來插入,更新和刪除訂單。
先建立服務,執行以下步驟:
1.創建一個新的 ASP.NET MVC 4 Web應用, 在嚮導中選擇Web API模板. 把項目命名為:Recipe3.Service.
2.向項目添加一個Web API 控制器,命名為:TravelAgentController.
3. 接下來,添加如Listing 9-12的TravelAgent和Booking實體類.
Listing 9-12. Travel Agent and Booking Entity Classes
public class TravelAgent
{
public TravelAgent()
{
this.Bookings = new HashSet<Booking>();
}
public int AgentId { get; set; }
public string Name { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
public class Booking
{
public int BookingId { get; set; }
public int AgentId { get; set; }
public string Customer { get; set; }
public DateTime BookingDate { get; set; }
public bool Paid { get; set; }
public virtual TravelAgent TravelAgent { get; set; }
}
4. 在“Recipe1.Service ”項目中添加EF6的引用。最好是藉助 NuGet 包管理器來添加。在”引用”上右擊,選擇”管理 NuGet 程式包.從“聯機”標簽頁,定位並安裝EF6包。這樣將會下載,安裝並配置好EF6庫到你的項目中。.
5. 添加一個類,命名為:Recipe3Context, 添加如Listing 9-13的代碼,
確保它繼承DbContext類.
Listing 9-13. Context Class
public class Recipe3Context : DbContext
{
public Recipe3Context() : base("Recipe3ConnectionString") { }
public DbSet<TravelAgent> TravelAgents { get; set; }
public DbSet<Booking> Bookings { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TravelAgent>().HasKey(x => x.AgentId);
modelBuilder.Entity<TravelAgent>().ToTable("Chapter9.TravelAgent");
modelBuilder.Entity<Booking>().ToTable("Chapter9.Booking");
}
}
6. 接著, 把如Listing 9-14的Recipe3ConnectionString連接字元串添加到Web.Config文件里ConnectionStrings節里.
Listing 9-14. Web API 服務里的Recipe3Context的連接字元串
<connectionStrings>
<add name="Recipe3ConnectionString"
connectionString="Data Source=.;
Initial Catalog=EFRecipes;
Integrated Security=True;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
7. 把Listing 9-15里的代碼插入到Global.asax的Application_Start 方法里. 這些代碼禁止EF進行模型相容性檢查和指示JSON序列時忽略由TravelAgent 和Booking類之間導航屬性的雙向引用所引來的迴圈引用問題。Listing 9-15. Disable the Entity Framework Model Compatibility Check
protected void Application_Start()
{
//禁止EF進行模型相容性檢查
Database.SetInitializer<Recipe3Context>(null);
//實體之間導航屬性如果迴圈引用會使web api在進行Json序列化一個對象時出錯,這是Json.net在序列//時預設情況。為瞭解決這個問題,簡單的配置JSON序列化器忽略迴圈引用。
GlobalConfiguration.Configuration.Formatters.JsonFormatter
.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
...
}
8. 依照Listing 9-16修改Web API的RouteConfig.cs文件的路由配置
Listing 9-16. Modifications to RouteConfig Class to Accommodate RPC-Style Routing
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionMethodSave",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
9. 最後, 用Listing 9-17里的代碼替換TravelAgentController里的代碼
Listing 9-17. Travel Agent Web API Controller
public class TravelAgentController : ApiController
{
// GET api/travelagent
[HttpGet]
public IEnumerable<TravelAgent> Retrieve()
{
using (var context = new Recipe3Context())
{
return context.TravelAgents.Include(x => x.Bookings).ToList();
}
}
/// <summary>
/// 通過Web API 的路由,執行該更新 TravelAgent的方法
/// </summary>
public HttpResponseMessage Update(TravelAgent travelAgent)
{
using (var context = new Recipe3Context())
{
var newParentEntity = true;
// 添加一個實體,並給它的對象圖(包含父與子實體)設置一個State值,讓context知道哪些實體需要更新
context.TravelAgents.Add(travelAgent);
if (travelAgent.AgentId > 0)
{
// ID值大於0,表示這是一個已經存在於資料庫的時候,我們要把該實體的state設置為updated
context.Entry(travelAgent).State = EntityState.Modified;
newParentEntity = false;
}
//通過迭代子實體,並分配正確的state.
foreach (var booking in travelAgent.Bookings)
{
if (booking.BookingId > 0)
// ID值大於0,表示booking已經存在,並把該實體的State設置為Modified.
context.Entry(booking).State = EntityState.Modified;
}
context.SaveChanges();
HttpResponseMessage response;
//根據實體State設置Http狀態碼
response = Request.CreateResponse(newParentEntity
? HttpStatusCode.Created : HttpStatusCode.OK, travelAgent);
return response;
}
}
[HttpDelete]
public HttpResponseMessage Cleanup()
{
using (var context = new Recipe3Context())
{
context.Database.ExecuteSqlCommand("delete from chapter9.booking");
context.Database.ExecuteSqlCommand("delete from chapter9.travelagent");
}
return Request.CreateResponse(HttpStatusCode.OK);
}
}
接下來我們創建調用上述服務的客戶端.
10. 創建一個解決方案,添加一個控制台應用程式,命名為: Recipe3.Client.
11.用Listing 9-18的代碼program.cs里的代碼
Listing 9-18. Our Windows Console Application That Serves as Our Test Client
internal class Program
{
private HttpClient _client;
private TravelAgent _agent1, _agent2;
private Booking _booking1, _booking2, _booking3;
private HttpResponseMessage _response;
private static void Main()
{
Task t = Run();
t.Wait();
Console.WriteLine("\nPress <enter> to continue...");
Console.ReadLine();
}
private static async Task Run()
{
var program = new Program();
program.ServiceSetup();
//在清除之前數據以前,不往下執行
await program.CleanupAsync();
program.CreateFirstAgent();
//在創建agent前,不往下執行
await program.AddAgentAsync();
program.CreateSecondAgent();
//在創建agent前,不往下執行
await program.AddSecondAgentAsync();
program.ModifyAgent();
// 在更新agent前,不往下執行
await program.UpdateAgentAsync();
// do not proceed until agents are fetched
await program.FetchAgentsAsync();
}
private void ServiceSetup()
{
// 構造Web API的調用實例
_client = new HttpClient {BaseAddress = new Uri("http://localhost:6687/")};
// 添加接收頭部媒體類型,使請求能接收由Web API返回的Json格式資源_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
private async Task CleanupAsync()
{
//調用服務端的cleanup方法
_response = await _client.DeleteAsync("api/travelagent/cleanup/");
}
private void CreateFirstAgent()
{
// 創建新的TravelAgent和booking對象
_agent1 = new TravelAgent {Name = "John Tate"};
_booking1 = new Booking
{
Customer = "Karen Stevens",
Paid = false,
BookingDate = DateTime.Parse("2/2/2010")
};
_booking2 = new Booking
{
Customer = "Dolly Parton",
Paid = true,
BookingDate = DateTime.Parse("3/10/2010")
};
_agent1.Bookings.Add(_booking1);
_agent1.Bookings.Add(_booking2);
}
private async Task AddAgentAsync()
{
//調用Web API服務中普通的update方法來添加agent和bookings
_response = await _client.PostAsync("api/travelagent/update/",
_agent1, new JsonMediaTypeFormatter());
if (_response.IsSuccessStatusCode)
{
//從服務端獲取新創建的travel agent對象,它包含由資料庫自增ID值
_agent1 = await _response.Content.ReadAsAsync<TravelAgent>();
_booking1 = _agent1.Bookings.FirstOrDefault(x => x.Customer == "Karen Stevens");
_booking2 = _agent1.Bookings.FirstOrDefault(x => x.Customer == "Dolly Parton");
Console.WriteLine("Successfully created Travel Agent {0} and {1} Booking(s)",
_agent1.Name, _agent1.Bookings.Count);
}
else
Console.WriteLine("{0} ({1})", (int) _response.StatusCode, _response.ReasonPhrase);
}
private void CreateSecondAgent()
{
// 創建新的agent和booking對象
_agent2 = new TravelAgent {Name = "Perry Como"};
_booking3 = new Booking
{
Customer = "Loretta Lynn",
Paid = true,
BookingDate = DateTime.Parse("3/15/2010")
};
_agent2.Bookings.Add(_booking3);
}
private async Task AddSecondAgentAsync()
{
// 調用Web API 服務中普通的update 方法,來添加 agent 和booking
_response = await _client.PostAsync("api/travelagent/update/",
_agent2, new JsonMediaTypeFormatter());
if (_response.IsSuccessStatusCode)
{
//從服務端獲取新創建的travel agent對象,它包含由資料庫自增ID值
_agent2 = await _response.Content.ReadAsAsync<TravelAgent>();
_booking3 = _agent2.Bookings.FirstOrDefault(x => x.Customer == "Loretta Lynn");
Console.WriteLine("Successfully created Travel Agent {0} and {1} Booking(s)",
_agent2.Name, _agent2.Bookings.Count);
}
else
Console.WriteLine("{0} ({1})", (int) _response.StatusCode, _response.ReasonPhrase);
}
private void ModifyAgent()
{
//修改agent 2的Name屬性,並添加一個booking 1
_agent2.Name = "Perry Como, Jr.";
_agent2.Bookings.Add(_booking1);
}
private async Task UpdateAgentAsync()
{
// 調用Web API 服務中普通的update 方法,來更新 agent 2
_response = await _client.PostAsync("api/travelagent/update/",
_agent2, new JsonMediaTypeFormatter());
if (_response.IsSuccessStatusCode)
{
// 獲取包含新ID值的從服務端返回的travel agent
_agent1 = _response.Content.ReadAsAsync<TravelAgent>().Result;
Console.WriteLine("Successfully updated Travel Agent {0} and {1} Booking(s)",
_agent1.Name, _agent1.Bookings.Count);
}
else
Console.WriteLine("{0} ({1})", (int) _response.StatusCode, _response.ReasonPhrase);
}
private async Task FetchAgentsAsync()
{
//調用服務端的Get方法,獲取所有 Travel Agents 和 Bookings
_response = _client.GetAsync("api/travelagent/retrieve").Result;
if (_response.IsSuccessStatusCode)
{
//獲取從服務端返回的包含ID值的新創建的 travel agent
var agents = await _response.Content.ReadAsAsync<IEnumerable<TravelAgent>>();
foreach (var agent in agents)
{
Console.WriteLine("Travel Agent {0} has {1} Booking(s)", agent.Name,
agent.Bookings.Count());
}
}
else
Console.WriteLine("{0} ({1})", (int) _response.StatusCode, _response.ReasonPhrase);
}
}
12. 最後,添加與服務端也就是Listing 9-12所列的相同的 TravelAgent 和Booking 類
以下Listing 9-18,是客戶端輸出結果:
============================================================================
Successfully created Travel Agent John Tate and 2 Booking(s)
Successfully created Travel Agent Perry Como and 1 Booking(s)
Successfully updated Travel Agent Perry Como, Jr. and 2 Booking(s)
Travel Agent John Tate has 1 Booking(s)
Travel Agent Perry Como, Jr. has 2 Booking(s)
=============================================================================
它是如何工作的
先運行Web API應用程式. 啟動後會打開首頁.至此, 網站已經在運行,並且服務已經可以使用.接著打開控制台項目, 在program.cs 首頁設置斷點, 運行控制台應用程式. 首先建立與服務端的管道連接,並配置請求頭部媒體類型,使它能接收JSON格式,接著客戶端執行DeleteAsync方法,它會調用Web API 中TravelAgent 控制器里的Cleanup方法,該方法會刪除資料庫表中的所有之前的數據。接著我們在客戶端新建一個travel agent和兩個booking對象,HttpClient對象調用PostAsync方法,向服務端傳遞這三個新建的對象,如果你在Web API的TravelAgent控制Update方法前加斷點,你將會看到它的參數接收到TravelAgent以及它所包含的booking對象。Update方法會給TravelAgent做上Added或Modified的標誌,而Context就會跟蹤這些對象。
■■註意:你可能會用Add或Attach一組新的實體對象(例如:多個Booking的Id都為0)
.如果用Attach,EF會因為主鍵衝突拋出一個異常。
我們判斷ID值為0,表示實體State是Added的,否則為Modified,我們又額外的利用newParentEntity變數作為是否為新實體的標誌,以便正確返回Http狀態碼。
接著迭代TravelAgent所包含的booking實體,並給它們也做上Added或Modified的標誌,
接著調用 SaveChanges 方法, 它會為Added狀態實體生成插入語句,為Modified狀態實體生成更新語句,然後,如果TravelAgent為Added返回http狀態碼201,如果為Modified返回200。狀態碼告知它的調用者操作已經成功完成
. 當分佈基於REST服務時,最好是通過Http狀態碼來告知它的調用者操作的執行情況.
隨後我們在客戶端添加另一個新的travel agent和booking,利用PostAsync方法調用服務端的Update方法。
接著, 我們修改第二個Travel agent 實體的Name屬性,並從第一個Travel agent 實體中移一個booking實體過來,此次我們調用 Update 方法時, 每個實體Id都有大於0的值, 所以會把這些實體的state設置為modified,所以保存時EF會成成Update的sql語句
最後,客戶端通過httpclient的GetAsync方法調用服務端的 Retrieve 方法.該方法返回所有的travel agent 和booking 實體,此處我們簡單的用Include()方法預先載入booking實體。
需要知道的是: JSON序列化器將會序列化實體的所有Public屬性,即使你只投射(例如Select幾個欄位)幾個屬性。
本節, 我們封裝EF的操作到一個Web API服務里.而客戶端可以用HttpClient對象調用這些服務。這個例子里, 我們沒有優先採用 Web API的 HTTP基於動作的分佈方式,而是更多地採用基於RPC的路由方式
. 在實際項目中,你可能更喜歡利用HTTP的基於動作的方式, 因為它更符合 ASP.NET Web API的基於REST服務的意圖。
在實際項目中,我們可能更樂意為EF數據訪問單獨創建一個層(Visual Studio類庫),從而使它從Web API服務中剝離出來。