Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying entities throws "Invalid Operation Exception" on enum field

I was just trying some features of entity framework 5 and kendo ui. I have a following ProductType enum

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

This enum type is one of the field in the Product Entity.

[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;}

}

The ProductType column in the underlying SQL Server Database is defined as (tinyint, not null).

I access list of Products in the following Controller Action of 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);
        }
    }

Here is the description of the InvalidOperationException that is thrown on products.ToList() in the above controller action.

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'.

Any guesses why ToList() is throwing an InvalidOperationException.

Just for info, the Database existed previously, and the Entities were manually coded based on the Database as POCO's.

Edit

Here is the complete exception details

  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: 
like image 218
Jatin Avatar asked Dec 05 '22 07:12

Jatin


1 Answers

There is a mismatch between the enum type which in your case is int based and your database where the column is byte (tinyint) based. You can fix this by setting the correct underlying type of your enum type:

public enum ProductType : byte
{
...
}
like image 64
Pawel Avatar answered Jan 07 '23 00:01

Pawel