2014-08-29 94 views
2

我有一个返回List的WCF服务。WCF OperationContract返回列表<CustomType>

[DataContract] 
public class EmployeesVM 
{ 
    [DataMember] 
    public int ID { get; set; } 
    [DataMember] 
    public string Name { get; set; } 
} 

我正在使用EF将Employees列表返回给此类。在我的WCF服务我使用:

public IList<EmployessVM> getEmployees() 
    { 
     using (var dbContext = new SecEntities()) 
     { 
      return (from e in dbContext.Employees 
        select new EmployeesVM { 
         ID = e.ID, 
         Name = e.Name 
        }).ToList(); 
     } 
    } 

在我的Windows Phone 8的客户端应用程序,我需要从方法列表。

void proxy_getEmployeesCompleted(object sender, GetDataService.getEmployeesCompletedEventArgs e) 
    { 
     if (e.Result != null) 
     { 
      List<ViewModel.EmployeesVM> resultList = e.Result.ToList(); 
     } 
    } 

在我的WP的ViewModel文件夹我有相同的类型:

public class EmployeesVM 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

但是,当我尝试编译我得到这个错误:

Cannot implicitly convert type  'System.Collections.Generic.List<SisSeguranca.GetDataService.EmployeesVM>' to 'System.Collections.Generic.List<SisSeguranca.ViewModel.EmployeesVM>' 

我已经试过这也一样,并没有奏效。

List<ViewModel.EmployeesVM> lista = (ViewModel.EmployeesVM)e.Result.ToList(); 

我怎么能转换成具有相同的字段和名字我的客户端应用程序类型在WCF服务返回的类型?

+0

可以在客户端和服务中使用相同的类型,也可以使用映射库。对我来说,我通常会返回一个DTO类,它出现在服务器和客户端上,并映射到模型中的实体类。 – Mashton 2014-08-29 14:00:30

回答

3

我相信你使用Visual Studio添加服务引用选项创建服务引用。这将为您的WCF服务创建代理类。它也似乎是你的项目中已经存在/引用了一个类似的类。这就是你遇到错误的原因。有一个选项可以重用现有类型。启用该功能。

参见:How to: Configure a Service to Reuse Existing Types

enter image description here

另一种选择是在一个单独的项目单独的合同和相关实体

参见:Things to Consider When Designing a WCF Contract

The first recommendation is to separate logically related interfaces, contracts, entities, messages, and enumerations into a separate project. One way to do this is to add a class library project to your solution and name it after your service name, with the word "Contracts" appended to it. An example of this is WcfService1.Contracts.

您可以参考该DLL /项目在您的WCF服务以及您的项目使用该服务。

+0

+1但是你也可以提到,在服务和客户端之间共享对象时,最好的做法是将'DataContract'对象移动到它们自己的程序集中,以便在此过程中使用。 – toadflakz 2014-08-29 15:14:50

+0

@toadflakz,这是一个很好的建议,并在参考答案中加入了这个答案。 – Habib 2014-08-29 15:18:45

+1

@Habib我创建了一个类库(可移植),并将我的类添加到此项目中,并在项目之间添加了引用并重新创建了服务引用。现在它工作了! – 2014-08-29 16:20:28

0

您正在创建两个名为“EmployeesVM”的类您需要做的是将此类拉出到您的“服务器”和Windows Phone共享的DLL中。

+0

这甚至不需要。使用适当的WCF设置,您也可以在本地模型中使用您的WCF服务所使用的类。如果您从Visual Studio的默认WCF项目开始,则已包含此项目。然后你只需要在项目中添加web服务作为服务引用。 – Nzall 2014-08-29 14:02:36