Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error message Nullable object must have a value

Tags:

c#

asp.net

I have a null error on my DTO object at runtime:

enter image description here

I didn't understand because column is nullable:

[DataContract]
public class SearchParametersCompanyDTO
{
    public SearchParametersCompanyDTO();

    [DataMember]
    public CompanyColumnsEnumDTO? Column { get; set; }
    [DataMember]
    public int PageIndex { get; set; }
    [DataMember]
    public int PageSize { get; set; }
    [DataMember]
    public string Term { get; set; }
}

[DataContract]
public enum CompanyColumnsEnumDTO
{
    [EnumMember]
    CompanyName = 0,
    [EnumMember]
    City = 1,
    [EnumMember]
    PostCode = 2,
}

It must be a conversion problem because null is accepted on Column:

        var dto = new SearchParametersCompanyDTO
        {
            PageIndex = pageIndex,
            PageSize = defaultPageSize,
            Term = term,
            Column = null
        };

Any idea?

like image 968
Bronzato Avatar asked Apr 12 '12 14:04

Bronzato


2 Answers

You're trying to cast a null value to an enum type (rather than a nullable enum type). I'm guessing you actually want to change your cast to:

Column = (CompanyColumnsEnumDTO?) column
like image 96
Justin Niessner Avatar answered Oct 27 '22 00:10

Justin Niessner


The problem here is you're casting the value column into a non-nullable value CompanyColumnsEnumDTO. Based on the exception it looks like column is null here and casting to a non-null appropriately throws an exception. Did you mean to cast to CompanyColumnsEnumDTO? instead?

like image 25
JaredPar Avatar answered Oct 27 '22 00:10

JaredPar