查询实体会在枚举字段上引发“无效操作异常”

时间:2014-02-05 12:59:01

标签: entity-framework ef-code-first entity-framework-5

我只是尝试了实体框架5和kendo ui的一些功能。我有以下 ProductType 枚举

public enum ProductType {
    [Description("Hazardous")]
    Hazardous,
    [Description("Non Hazardous")]
    NonHazardous
}

此枚举类型是产品实体中的字段之一。

[Table("Products")]
public class Product {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    //Other Fields ...

    [Required(ErrorMessage="Product Type is Required")]
    public ProductType ProductType {get;set;}

}

基础SQL Server数据库中的ProductType列定义为(tinyint,not null)

我在MVC的以下控制器操作中访问产品列表

    public ActionResult _ProductList(int pageSize, int skip) {
        using (WorkUnit workUnit = new WorkUnit()) {
            IQueryable<Product> products = workUnit.ProductRepository.GetAllProducts()
                                                   .Include(p => p.Category);
            int total = products.Count();
            List<Product> productList = products.ToList<Product>(); //Throws InvalidOperationException
            return Json(new { total = total, data = productList }, JsonRequestBehavior.AllowGet);
        }
    }

以上是上述控制器操作中 products.ToList()引发的InvalidOperationException的描述。

The 'ProductType' property on 'Product' could not be set to a 'Byte' value. 
You must set this property to a non-null value of type 'ProductType'.

任何猜测 ToList()为什么会抛出 InvalidOperationException

仅供参考,数据库以前存在,实体是根据数据库手动编码为POCO的。

修改

以下是完整的异常详情

  System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=The 'ProductType' property on 'Product' could not be set to a 'Byte' value. You must set this property to a non-null value of type 'ProductType'. 
  Source=System.Data.Entity
  StackTrace:
       at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
       at System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
       at lambda_method(Closure , Shaper )
       at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
       at lambda_method(Closure , Shaper )
       at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
       at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at KendoUI_Web_Demo.Controllers.HomeController._ProductList(Int32 pageSize, Int32 skip) in d:\Practice\ASP.NET_MVC\KendoUI_Web_Demo\KendoUI_Web_Demo\Controllers\HomeController.cs:line 52
       at lambda_method(Closure , ControllerBase , Object[] )
       at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
       at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
       at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
       at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
  InnerException: 

1 个答案:

答案 0 :(得分:16)

在您的情况下基于int的枚举类型与基于字节(tinyint)的列的数据库之间存在不匹配。您可以通过设置枚举类型的正确基础类型来解决此问题:

public enum ProductType : byte
{
...
}