WCF exposing generic type 'T'

2020-02-06 07:44发布

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;        
}

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

标签: wcf
3条回答
叼着烟拽天下
2楼-- · 2020-02-06 08:11

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.

查看更多
老娘就宠你
3楼-- · 2020-02-06 08:15

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

查看更多
太酷不给撩
4楼-- · 2020-02-06 08:16
  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.

查看更多
登录 后发表回答