6

I kept getting the error message below while trying to retrieve data using entity framework and assigning to my custom class Customer

cannot convert source type 'system.nullable' to target type 'int'

CustomerNumber and Route have datatypes of Int32 and the fields in the database allows nulls

        select new Customer()
            {
                AccountListId = j.cost1,
                Csr = j.cost2,
                CustomerName = j.cost3,
                Address = j.cost4,
                Telephone = j.cost5,
                Contact = j.cost6,
                CustomerNumber = j.cost7,
                Branch = j.cost8,
                Route = j.cost9,
            }).ToList<Customer>();

How can I handle this?

2
  • And what would you like to assign to the Int32 fields if the value from the database is null. Obviously, null is not valid. Do you want to set 0 or -1, or what?
    – sstan
    Jul 3, 2015 at 23:59
  • possible duplicate of How to convert nullable int to int Jul 4, 2015 at 1:18

3 Answers 3

5

Apparently, j.cost7 and j.cost9 are of type Nullable<Int32>. I am assuming, because you haven't shown us.

Obviously, you can't assign a Nullable<Int32> to an Int32 type, because, what do you do if the value is null? The compiler doesn't know. You need to decide what to do in that case, and code accordingly.

Let's say you decide to assign -1 as a default value in case of a null value in the database, then you can use the null-coalescing operator and do something like this:

    select new Customer()
        {
            AccountListId = j.cost1,
            Csr = j.cost2,
            CustomerName = j.cost3,
            Address = j.cost4,
            Telephone = j.cost5,
            Contact = j.cost6,
            CustomerNumber = j.cost7 ?? -1,
            Branch = j.cost8,
            Route = j.cost9 ?? -1,
        }).ToList<Customer>();

If, what you really want, is to be able to store the null value if there is one, then change the type of CustomerNumber and Route from Int32 to Nullable<Int32>, or using an alternate syntax: int?.

1
  • 1
    What if I know j.cost7 is never null? Say, I've set it to nullable for purposes of validation and I know that asp net core will reject all models whose j.cost7 is null. Why doesn't the null forigiving operator work in this case? eg. CustomerNumber = j.cost7!,
    – user10706046
    Oct 5, 2021 at 18:14
1

You can use the default value of an int.

Eg:

CustomerNumber = j.cost7 ?? default(int),
        Branch = j.cost8,
        Route = j.cost9 ?? default(int),
0

Try

if (j.cost7 == null)
{
    CustomerNumber = 0;
}
else
{
    CustomerNumber = j.cost7
}
1
  • That's not gonna work, syntactically, in a with constructor. Jul 4, 2015 at 1:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.