有一個3層的WPF應用程序的架構不同的解決方案,但在這裏是一種可能性:
1+ 2)一種解決方案是創建代表您的客戶端應用程序實際需要的「中間」對象。 舉例來說,如果你的應用程序需要顯示有關產品加上相關的客戶名稱的信息,你可以建立以下對象:
public MyProduct
{
// Properties of the product itself
public int ProductID { get; set; }
public string ProductName { get; set; }
...
// Properties that come from the Customer entity
public string CustomerName { get; set; }
}
然後,您可以公開,從一個ID返回你的產品一個無狀態的WCF服務:
[ServiceContract]
MyProduct GetProductByID(int productID);
在應用程序的服務器端(即你的服務的實現),你可以返回一個MyProduct
例如建立通過查詢通過EF數據庫(每次調用一個上下文):
public MyProduct GetProductByID(int productID)
{
using (DBContext ctx = new ....)
{
return from p in ctx.Products
where p.ID == productID
select new MyProduct
{
ProductID = p.ID,
ProductName = p.Name,
CustomerName = p.Customer.Name // Inner join here
};
}
}
3)在WCF服務和ViewModel之間添加額外的層可能被認爲是過度工程。恕我直言,可以直接從ViewModel調用WCF服務。WCF生成的客戶端代理代碼具有模型的實際角色(至少是模型的一部分)。
編輯:
爲什麼myProduct的應引用客戶名稱,而不是 Customer.In我的情況下,客戶將有很多屬性我工作 用。這個「映射」是不是太貴了?
您可以使用實際的實體。但在客戶端,由於它是三層架構,因此您無法通過導航屬性訪問數據庫。如果嵌套的Customer
屬性(類型爲Customer
),客戶端將有權訪問theProduct.Customer.Products
,這是沒有意義的,你不能以這種方式延遲加載實體(在客戶端沒有數據庫上下文)。
平坦的「中間」POCO更簡單IMO。沒有性能問題,映射非常簡單,與數據庫請求時間相比,此特定操作的CPU使用率無限小。
你可能想閱讀我的回答http://stackoverflow.com/q/10437241/50079 – Jon 2012-07-11 12:46:33
@Jon:你的答案確實很棒,謝謝。但是我還沒有完全清楚模型部分,參見。我的答案ken2k – LaurentH 2012-07-11 13:59:23