LINQ: Cannot convert short to short?

Cannot implicitly convert type 'short?' to 'short' at LocalAmount = t.EmpNo. I used Convert.ToInt16(t.EmpNo) but then the 'join' clause will get an error and be "incorrect", "type inference failed..."

    public class AccountTransaction
    {
        public Int16 LocalAmount { get; set; }
        public String AccountNumber { get; set; }
    }

    public static IEnumerable<AccountTransaction> GetAllTransactions()
    {
        using (var context = new SQL_TA_SCOREBOARDEntities1())
        {
            return (from t in context.EmployeeAccesses
                    join acc in context.View_HCM
                         on t.EmpNo equals acc.EmpNo
                    select new AccountTransaction
                    {
                        LocalAmount = t.EmpNo,
                        AccountNumber = acc.EmailAddress

                    }).ToList();
        }
    }

Answers


Your error message states that t.EmpNo is a nullable Int 16. See the questionmark behind short?

'short?' to 'short' - Which says: I can not convert a Int16? to an Int16 The question mark defines, that this value can be null.

So if you change your model, you do not need to parse anything, but you need to use t.EmpNo.Value

public class AccountTransaction
{
    public Int16? LocalAmount { get; set; }
    public String AccountNumber { get; set; }
}

It's likely that EmpNo should never be null, and that one of your EmpNo's is nullable in the database while the other is not. Make sure both are not nullable. If, for some reason they should be able to be Null sometimes, then they must both be nullable in the db. If this was happening and you fixed it in the db, you will have to reload your entity framework model and try your code again. You may need to change public Int16? LocalAmount { get; set; } back to public Int16 LocalAmount { get; set; }.

Essentially: Empno must be non nullable everywhere or nullable everywhere. In the database and the code.


Need Your Help