我正在使用 EF 6.0 开发一个 .NET 项目。
** 请注意,数据库已经存在,无法通过代码更改 **
我正在使用枚举,这是我的代码:
[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 位)。
关于c# - 错误消息将使用枚举与 EF 和 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546697/