Chrstpsln
Chrstpsln

Reputation: 777

Error message will using enum with EF and Web API

I'm working on a .NET project with EF 6.0.

** Please note that the database already exist and cannot be changed by code **

I'm using enum and here's my code :

[Table("T_PRODUCTS")]
public class basket
{
    [Key]
    public int productID{get;set;}
    public string productName {get;set;}
    public EProductType productType {get;set;}
}

public enum EProductType
{
    typeA = 0,
    typeB = 1,
}

And the definition of my table in SQL Server :

CREATE TABLE [dbo].[T_PRODUCTS](
    [productID] [int] NOT NULL,
    [productName] [varchar](100) NULL,
    [productType] [smallint] NULL,
CONSTRAINT [PK_T_PRODUCTS] PRIMARY KEY CLUSTERED 
(
    [productID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]  

While running unit tests, data are saved successfully in the database! ;)

however, when I use my web api :

public class ProductController : ApiController
{
    public HttpResponseMessage Get( int id )
    {
        var Product=  Products.GetById( id );

        if ( Product == null )
        {
            return Request.CreateResponse( HttpStatusCode.NotFound );
        }

        return Request.CreateResponse( HttpStatusCode.OK, Product );
    }       
}

I have this error message :

<Error><Message>An error as occured.</Message><ExceptionMessage>Property 'productType' on 'Product' could not be set to 'System.Int16'. You must assign a non null value of type 'EProductType' to this property. </ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>

If I change my enum like this :

public enum EProductType : ushort
{
    typeA = 0,
    typeB = 1,
}

It will return my product without error.

But, the field 'productType' is always set to 0 (zero). And then, all new product saved with EF have NULL in the field 'productType'...

How can I use enums with EF and a Web api ?

Thanks for your replies.

Upvotes: 2

Views: 2070

Answers (1)

Thomas Weller
Thomas Weller

Reputation: 11717

This is a simple type mismatch, there's nothing wrong in general.

Your [productType] column is of type smallint (16bit). Therefore you must use 16bit-integers in C# as well (which is short or ushort). Enums that do not explicitly derive from an integer type in C# are of type int (32bit) by default.

Upvotes: 4

Related Questions