开发者

WCF exposing generic type 'T'

I write a WCF service for Insert and delete operation here we used generic method but it gives following error "System.Runtime.Serialization.InvalidDataContractException: Type 'T' cannot be exported as a schema type because it is an open generic type. You can only export a generic type if all its generic parameter types are actual types."

here "EntityBase2" is base class for all entities

[ServiceContract]
[ServiceKnownType(typeof(EntityBase2))]
public interface IBackupUtility
{
    [OperationContract]
    void Delete<T>(T entity) where T : EntityBase2;

    [OperationContract]
    void InsertORUpdate<T>(T entity) where T : EntityBase2;        
}
开发者_如何学Python

Question is how i can expose generic type 'T'?


I think it is imposible, how could it generate the wsdl that way?

You have two options:

  • You could send the type as a parameter.

  • If you want to expose crud operations for entities I would recommend to use a code generator, maybe a T4 template for EF.


This post is old indeed, but maybe someone find this solution useful: WCF and Generics


  1. Answer to this question is both Yes and No. Yes for server prospective and No for client prospective.
  2. We can create a generic Data Contract on server but while using that in any operation contract we have to specify a data type of the generic.
  3. And at client end that data contract will be exposed only as a strongly data type not generic.

    [DataContract]
    public class MyGenericObject<T>
    {
       private T _id;
    
       [DataMember]
       public T ID
       {
          get { return _id; }
          set { _id = value; }
       }
    }
    
    [OperationContract]
    MyGenericObject<int> GetGenericObject();
    

This is what we have in Server we can see while using generic data contract we have to specify the type otherwise it’ll give compile time error.

On client what we get from WSDL is a follow:

[DataContract]
public class MyGenericObjectOfint

We can see here what we get from WSDL is not a generic data contract WSDL proxy generate a class with a new name using some convention.

Convention used is

Generic Class Name + "Of" + Type Parameter Name + Hash

Hash is not always generated, it’ll be generated only when there is a chance of name collision.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜