有一个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