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?

Baba
  • 2,059
  • 8
  • 48
  • 81
  • 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 03 '15 at 23:59
  • possible duplicate of [How to convert nullable int to int](http://stackoverflow.com/questions/5995317/how-to-convert-nullable-int-to-int) – M.kazem Akhgary Jul 04 '15 at 01:18

3 Answers3

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

sstan
  • 35,425
  • 6
  • 48
  • 66
  • 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!, –  Oct 05 '21 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),
Aniket Sharma
  • 1,000
  • 10
  • 16
0

Try

if (j.cost7 == null)
{
    CustomerNumber = 0;
}
else
{
    CustomerNumber = j.cost7
}
Jonah Mann
  • 23
  • 5