Entity Framework 6 Recipes 2nd Edition(9-2)译-用WCF更新单独分离的实体
9-2. 用WCF更新單獨(dú)分離的實(shí)體
問題
你想通過WCF為一個(gè)數(shù)據(jù)存儲發(fā)布查詢,插入,刪除和修改,并且使這些操作盡可能地簡單
此外,你想通過Code First方式實(shí)現(xiàn)EF6的數(shù)據(jù)訪問管理
?
解決方案
假設(shè)有如Figure 9-2所示模型.
?
Figure 9-2. 博客的posts(博文)和comments(評論)模型
模型表示博客的文章和評論之間的關(guān)系. 為了簡化,我們?nèi)サ袅撕芏鄬傩?#xff0c;像作者,發(fā)文時(shí)間等。我們想把所有的數(shù)據(jù)庫代碼封裝到WCF后,讓客戶端通過通過WCF讀取,更新,刪除,和插入Posts或Comments. 下面是創(chuàng)建WCF服務(wù)的步驟:
1. 創(chuàng)建一個(gè)新的Visual Studio 解決方案, 添加一個(gè) c# 類庫項(xiàng)目.并命名為Recipe2.
2. 在“Recipe1.Service ”項(xiàng)目中添加EF6的引用。最好是借助 NuGet 包管理器來添加。在”引用”上右擊,選擇”管理 NuGet 程序包.從“聯(lián)機(jī)”標(biāo)簽頁,定位并安裝EF6包。這樣將會下載,安裝并配置好EF6庫到你的項(xiàng)目中。
3. 向Recipe2項(xiàng)目添加三個(gè)類: Post, Comment, 和Recipe2Context. Post 和
Comment 用POCO 實(shí)體類,并直接遇到到Post 和 Comment 表. Recipe2Context是提供EF6服務(wù)的DbContext對象。確保WCF的實(shí)體類擁有
DataContract 和 DataMember 特性,如Listing 9-7所示.
Listing 9-7. POCO 類 Post, Comment,和 Recipe2Context
[DataContract(IsReference = true)]
public class Post
{
public Post()
{
Comments = new HashSet<Comment>();
}
[DataMember]
public int PostId { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public virtual ICollection<Comment> Comments { get; set; }
}
[DataContract(IsReference=true)]
public class Comment
{
[DataMember]
public int CommentId { get; set; }
[DataMember]
public int PostId { get; set; }
[DataMember]
public string CommentText { get; set; }
[DataMember]
public virtual Post Post { get; set; }
}
public class EFRecipesEntities : DbContext
{
public EFRecipesEntities()
: base("name= Recipe2ConnectionString")
{
}
???? public virtual DbSet<Post> Posts{get;set;}
???? public virtual DbSet<Comment> Comments{get;set;}
}
4. 向Recipe2項(xiàng)目中添加一個(gè) App.config 文件,把如 Listing 9-8所示的連接字符串復(fù)制進(jìn)去.
Listing 9-8. ??Recipe2類庫的連接字符串
<connectionStrings>
<add name="Recipe2ConnectionString"
connectionString="Data Source=.;
Initial Catalog=EFRecipes;
Integrated Security=True;
MultipleActiveResultSets=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
5. 向解決方案中添加一個(gè)WCF服務(wù)應(yīng)用程序. 使用默認(rèn)名稱Service1(譯注:vs2013默認(rèn)的是WcfService1)
. 用 Listing 9-9替換IService1.cs中的代碼
Listing 9-9. The Service Contract for Our Service
[ServiceContract]
public interface IService1
{
[OperationContract]
void Cleanup();
[OperationContract]
Post GetPostByTitle(string title);
[OperationContract]
Post SubmitPost(Post post);
[OperationContract]
Comment SubmitComment(Comment comment);
[OperationContract]
void DeleteComment(Comment comment);
}
6. 用Listing 9-10里的代碼替換 Service1.svc.cs 文件中的代碼. 添加對Recipe2類庫項(xiàng)目的引用,以便正確引用實(shí)體類. 添加EF6的引用.
用Listing 9-10所示代碼實(shí)現(xiàn)服務(wù)(確保項(xiàng)目引用了System.Data.Entity 和System.Security)
public class Service1 : IService
{
public void Cleanup()
{
using (var context = new EFRecipesEntities())
{
context.Database.ExecuteSqlCommand("delete from chapter9.comment");
context. Database.ExecuteSqlCommand ("delete from chapter9.post");
}
}
public Post GetPostByTitle(string title)
{
using (var context = new EFRecipesEntities())
{
context.Configuration.ProxyCreationEnabled = false;
var post = context.Posts.Include(p => p.Comments)
.Single(p => p.Title == title);
return post;
}
}
public Post SubmitPost(Post post)
{
using(var context=new EFRecipesEntities())//譯者:添加
{???????????????????????????????????????????????????????????????????????? //
context.Entry(post).State =
//id=0表示添加,其它情況表示更新
post.PostId == 0 ? EntityState.Added : EntityState.Modified;
context.SaveChanges();
return post;
}//譯者:添加
}
public Comment SubmitComment(Comment comment)
{
using (var context = new EFRecipesEntities())
{
context.Comments.Attach(comment);
if (comment.CommentId == 0)
{
// 插入
context.Entry(comment).State = EntityState.Added);
}
else
{
//設(shè)置單個(gè)屬性狀態(tài)為modified, 實(shí)體狀態(tài)也會是 modified, 但只更新單個(gè)的屬性,而不是整個(gè)實(shí)體
context.entry(comment).Property(x => x.CommentText).IsModified = true;
}
context.SaveChanges();
return comment;
}
}
public void DeleteComment(Comment comment)
{
using (var context = new EFRecipesEntities())
{
context.Entry(comment).State = EntityState.Deleted;
context.SaveChanges();
}
}
}
7.最后,添加一個(gè)windows控制臺項(xiàng)目,運(yùn)用它來測試WCF服務(wù),拷貝Listing 9-11里的代碼到Program類里,
. 右擊控制臺項(xiàng)目里的“引用”,選擇“添加服務(wù)引用”, 并選擇Service1 服務(wù)(譯注:在添加引用前,最好先生成一次服務(wù),不然可能出現(xiàn)引用不了的情況)
. 還需要添加第一步創(chuàng)建的Recipe2類庫項(xiàng)目.
Listing 9-11. Our Windows Console Application That Serves as Our Test Client
class Program
{
static void Main(string[] args)
{
using (var client = new ServiceReference2.Service1Client())
{
//清除之前的數(shù)據(jù)
client.Cleanup();
//插入一個(gè)Post
var post = new Post { Title = "POCO Proxies" };
post = client.SubmitPost(post);
// 更新這個(gè) post
post.Title = "Change Tracking Proxies";
client.SubmitPost(post);
// 添加一個(gè) comment
var comment1 = new Comment {
CommentText = "Virtual Properties are cool!",
PostId = post.PostId };
var comment2 = new Comment {
CommentText = "I use ICollection<T> all the time",
PostId = post.PostId };
comment1 = client.SubmitComment(comment1);
comment2 = client.SubmitComment(comment2);
?
// 更新一個(gè) comment
comment1.CommentText = "How do I use ICollection<T>?";
client.SubmitComment(comment1);
// 刪除comment 1
client.DeleteComment(comment1);
//獲取 posts的所有 comments
var p = client.GetPostByTitle("Change Tracking Proxies");
Console.WriteLine("Comments for post: {0}", p.Title);
foreach (var comment in p.Comments)
{
Console.WriteLine("\tComment: {0}", comment.CommentText);
}
}
}
}
?
譯注:有兩個(gè)地方一定要注意,1,Post,Comment類與數(shù)據(jù)庫的映射以及它們之間的關(guān)系,上述代碼中并未列出。2,需要把步驟4列出的連接字符串復(fù)制到Service1項(xiàng)目的web.config里.另:僅從9-1和9-2來看,發(fā)現(xiàn)原書有不少錯(cuò)誤,甚至是代碼上的,有些地方我直接修改過來,也沒特別作說明。
控制臺輸出的結(jié)果如下面的 Listing 9-11所示:
========================================================
Comments for post: Change Tracking Proxies
Comment: I use ICollection<T> all the time
========================================================
它是如何工作的?
啟動(dòng)我們用來測試WCF服務(wù)的控制臺項(xiàng)目,,創(chuàng)建一個(gè)WCF服務(wù)實(shí)例,因?yàn)槭褂胾sing{}塊,所以可以確保代碼執(zhí)行出此塊,會立即調(diào)用Dispose()。防止引起異常,我們調(diào)用Cleanup()方法,先把數(shù)據(jù)庫里已有的數(shù)據(jù)刪除,接下來兩行代碼,我們調(diào)用服務(wù)的SubmitPost()方法,(這個(gè)方法的實(shí)現(xiàn)查看Listing 9-10),該方法里先判斷PostId的值,如果為0,表示是一個(gè)新添加的Post對象,并把它的狀態(tài)設(shè)置為Added. 否則,它就是一個(gè)已存在于數(shù)據(jù)庫的Post對象,我們要對它進(jìn)行更新操作,因?yàn)榘阉臓顟B(tài)設(shè)置Modified. 盡管有幾分粗糙,但這種方法能判定Post對象狀態(tài)(是新的還是已存在的),相比ID依賴于整型在運(yùn)行時(shí)初始值為0,一個(gè)更好的方法是,傳遞一個(gè)額外的參數(shù)到SubmitPost()方法,或是創(chuàng)建一個(gè)單獨(dú)的InsertPost()方法。
最佳實(shí)踐:如果要插入這個(gè)post, 把它的state設(shè)置成EntityState.Added. 否則, 把它的state設(shè)置成EntityState.Modified. 根據(jù)EntityState值會產(chǎn)生一條Insert或是update的SQL語句。
在這個(gè)post對象插入后,該對象的PostId會變更成正確的值.
插入Comment或更新Comment一個(gè)單獨(dú)的屬性類似于插入或更新post,但有一個(gè)很在的不同:我們的業(yè)務(wù)規(guī)則是只更新comment的CommentText 屬性.該屬性包含comment的主體, 且我們不想更新其它屬性.因此,我們給CommentText 作上 modified標(biāo)志.EF將會生成一個(gè)簡單的只更新CommentText列的Sql語句.如果我們修改Comment多個(gè)屬性,我們就需要想辦法跟蹤到哪個(gè)屬性在客戶端被修改了. 但是用這種方式我們就不需要在客戶端用一個(gè)復(fù)雜的方法來跟蹤實(shí)體的哪個(gè)屬性發(fā)生變化。
?
為了刪除一個(gè) comment,我們調(diào)用context 對象的Entity() 方法, 并傳遞一個(gè)state被設(shè)置成Deleted 的 comment 作為參數(shù), 因?yàn)閏omment 被設(shè)置為Deleted,所以保存時(shí)會生成一條delete的SQL語句。
最后, GetPostByTitle() 為每個(gè)符合條件的Post預(yù)先加載所有,以post和相關(guān)的comments對象圖的形式返回. 因?yàn)槲覀儜?yīng)用了POCO類, 我們想要EF返回一個(gè)包含post和comment類的動(dòng)態(tài)代理對象.可惜的是, WCF 不能序列化一個(gè)代理對象. 然而我們把 ProxyCreationEnabled 設(shè)置成false, 就可以簡單的使代理類不質(zhì)疑EF實(shí)際返回的對象。如果我們企圖序列這個(gè)代理對象,會收到如下的錯(cuò)誤信息:
基礎(chǔ)連接已經(jīng)關(guān)閉: 服務(wù)器關(guān)閉了本應(yīng)保持活動(dòng)狀態(tài)的連接(譯注:測試過)。我們甚至可以在構(gòu)造函數(shù)中使用 ?ProxyCreationEnabled = false,迫使它在所有對所有服務(wù)方法有效果
在本節(jié), 我們通過WCF利用POCO對象進(jìn)行CRUD操作. 由于沒有保存客戶端的狀態(tài)信息,我們只能分別創(chuàng)建插入,修改,刪除post和comment的方法。
.在本章的其它節(jié)里我們將減少服務(wù)端的方法來簡化客戶端與服務(wù)器的通信。
附:創(chuàng)建示例用到的數(shù)據(jù)庫的腳本文件
?
總結(jié)
以上是生活随笔為你收集整理的Entity Framework 6 Recipes 2nd Edition(9-2)译-用WCF更新单独分离的实体的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 身为DATASHUO大数据工程师,我亲手
- 下一篇: 设计模式C#实现(十六)——中介者模式