Search code examples
c#asp.net-web-apiazure-service-fabric

Unable to pass an object with Enum Property from repository project to service fabric service


I have a Gender Enum and trying to pass it in an object from repository layer to service method. Though, I add EnumMember and DataContract attribute to it.

Getting below error.

Type 'MyNamespace.Gender' with data contract name 'Gender:http://schemas.datacontract.org/2004/07/MyNamespace' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.


Solution

  • You need to add a KnownType attribute to the DataContract class that is using the enum type.

    [DataContract]
    [KnownType(typeof(Shape))]
    public class CompanyLogo
    {
        [DataMember]
        private Shape ShapeOfLogo;
        [DataMember]
        private int ColorOfLogo;
    }
    

    This will expose the enum type in the WSDL so that the client of the service understands the type you are using.

    Alternatively you can cast the enum to its base type and expose it as an int instead of the enum value.