Bronzato
Bronzato

Reputation: 9332

Error message Nullable object must have a value

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?

Upvotes: 6

Views: 2651

Answers (3)

JaredPar
JaredPar

Reputation: 754545

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?

Upvotes: 3

KingCronus
KingCronus

Reputation: 4519

You need to cast to (CompanyColumnsEnumDTO?) instead of (CompanyColumnsEnumDTO)

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245389

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

Upvotes: 6

Related Questions