我有一個與雲中的CRM 2011進行通信的WCF服務。我使用提供的crmsvcutil.exe爲CRM中的所有對象生成實體。我有一個接口IProduct
,指向GetAllProducts()
,需要返回所有產品的列表。如果我在客戶端(C#控制檯應用程序)時通過我的服務,Linq查詢具有預期的產品列表。但是當它試圖將其返回給調用應用程序時,出現錯誤:WCF反序列化 - 反序列化器不知道映射到該名稱的任何類型
The InnerException message was 'Error in line 1 position 688. Element 'http://schemas.datacontract.org/2004/07/System.Collections.Generic:value' contains data from a type that maps to the name 'http://schemas.microsoft.com/xrm/2011/Contracts:OptionSetValue'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'OptionSetValue' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details."}
。
這隻發生在複雜的數據類型上。如果我返回一個簡單的字符串或int,那裏沒有問題。作爲可返回複雜類型的POC,我創建了一個名爲ComplexPerson
的類和一個名爲GetPerson(int Id)
的方法來返回一個簡單對象。這工作得很好(因爲我不得不自己裝飾課程)。
namespace Microsoft.ServiceModel.Samples
{
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface IProduct
{
[OperationContract]
[ServiceKnownType(typeof(Product))]
List<Product> GetAllProducts();
[OperationContract]
ComplexPerson GetPerson(int Id);
}
public class ProductService : IProduct
{
private List<Product> _products;
private OrganizationServiceProxy _serviceProxy;
private IOrganizationService _service;
public List<Product> GetAllProducts()
{
_products = new List<Product>();
try
{
//connect to crm
var query = orgContext.CreateQuery<Product>();
foreach (var p in query)
{
if (p is Product)
_products.Add(p as Product);
}
return _products;
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
// You can handle an exception here or pass it back to the calling method.
return null;
}
}
public ComplexPerson GetPerson(int Id)
{
ComplexPerson person = new ComplexPerson();
switch (Id)
{
case 2:
person.FirstName = "Tim";
person.LastName = "Gabrhel";
person.BirthDate = new DateTime(1987, 02, 13, 0, 0, 0);
break;
default:
break;
}
return person;
}
}
[DataContract]
public class ComplexPerson
{
[DataMember]
public string FirstName;
[DataMember]
public string LastName;
[DataMember]
public DateTime BirthDate;
public ComplexPerson()
{
}
}
}