我有一个与云中的 CRM 2011 通信的 WCF 服务。我使用提供的 crmsvcutil.exe 为 CRM 中的所有对象生成实体。我有一个接口IProduct
指向GetAllProducts()
需要返回所有产品的列表。如果我在客户端(C# 控制台应用程序)时通过我的服务,Linq 查询会按预期包含产品列表。但是当它试图将它返回给调用应用程序时,我得到一个错误:
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()
{
}
}
}