错误消息将使用带有EF和Web API的枚举
本文关键字:Web API 枚举 EF 消息 错误 | 更新日期: 2024-09-21 21:39:08
我正在用EF 6.0做一个.NET项目。
**请注意,数据库已存在,无法通过代码**进行更改
我使用enum,这是我的代码:
[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,
}
以及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]
运行单元测试时,数据成功保存在数据库中!)
然而,当我使用我的网络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 );
}
}
我有这个错误消息:
<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>
如果我这样更改我的枚举:
public enum EProductType : ushort
{
typeA = 0,
typeB = 1,
}
它会毫无差错地退回我的产品。
但是,字段"productType"始终设置为0(零)。然后,所有用EF保存的新产品在字段"productType"中都有NULL。。。
如何将枚举与EF和Web api一起使用?
谢谢你的回复。
这是一个简单的类型不匹配,通常没有什么问题。
您的[productType]
列的类型为smallint
(16位)。因此,您也必须在C#中使用16位整数(即short
或ushort
)。默认情况下,没有从C#中的整数类型显式派生的枚举的类型为int
(32位)。