简体   繁体   中英

Cannot convert source type system.nullable to target type int

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?

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

Try

if (j.cost7 == null)
{
    CustomerNumber = 0;
}
else
{
    CustomerNumber = j.cost7
}

You can use the default value of an int.

Eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM