1

I have a variable status defined in following entity:

public class Item
    {
        public string ItemNumber { get; set; }
        public string ItemDescription { get; set; }
        public int ItemId { get; set; }
        public Status status { get; set; }
    }

Enum:

public enum Status
    {
        Approved = 1,
        Received = 2,
        Issued = 3,
        PendingApproval = 4,
        Rejected = 5,
        Invoiced = 6,
        Transfered = 7
    }

this is the linq:

IEnumerable<Item> rpo = (from ro in _db.rpo.Where(c=> c.Id == WorkingId))
                         select new Items 
                         {
                           ItemId = ro.Id
                           ItemDescription = ro.Description
                           ItemNum = ro.Number
                           ItemStatus = ro.Status
                         }.ToList();

I am getting this error at linq

The cast to value type 'Enum' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

Kindly let me know how to set the nullable type for the parameter

Updated the question

khan88
  • 109
  • 1
  • 2
  • 9

2 Answers2

3

You can check in your query if the retrieved value is null:

IEnumerable<Item> rpo = (from ro in _db.rpo.Where(c=> c.Id == WorkingId))
                         select new Items 
                         {
                           ItemId = ro.Id
                           ItemDescription = ro.Description
                           ItemNum = ro.Number
                           ItemStatus = ro.Status ?? Status.None
                         }.ToList();

Where you have a new value in your enum, None. Or you choose one of the existing values.

The ?? checks if the variable in front of ?? is null. If it isn't, use that value, else use the value specified after ??. More info here

Ofcourse, your ro.Status has to be Nullable to check if it can be null.

Loetn
  • 3,832
  • 25
  • 41
  • I tried your answer but then the error at ro.Status (Status is the column in DB of Type int.) says Left operand of '??' operator should be of reference or nullable. Any suggestion to work around this issue? – khan88 Mar 06 '15 at 09:39
  • Set the status column as nullable – Galma88 Mar 06 '15 at 09:42
1

Since an enum is a value type, it cannot be null. A way around that is to use a nullable type instead:

public System.Nullable<Status> Status { get; set; }

or the shorthand syntax:

public Status? Status { get; set; }

This can be done for any value type (int, bool, double etc.).

A nullable type exposes the properties HasValue and Value which allows you to check whether an actual valid value has been assigned.

Siewers
  • 22,626
  • 3
  • 20
  • 31
DarkWanderer
  • 8,739
  • 1
  • 25
  • 56