简体   繁体   English

LINQ:不能将空头转换为空头吗?

[英]LINQ: Cannot convert short to short?

Cannot implicitly convert type 'short?' 无法隐式转换类型“ short”? to 'short' at LocalAmount = t.EmpNo . LocalAmount = t.EmpNo处“短”。 I used Convert.ToInt16(t.EmpNo) but then the 'join' clause will get an error and be "incorrect", "type inference failed..." 我使用了Convert.ToInt16(t.EmpNo)但随后的'join'子句将出现错误,并且是"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();
        }
    }

Your error message states that t.EmpNo is a nullable Int 16. See the questionmark behind short? 您的错误消息指出t.EmpNo是null的 Int16。请参见short后面的问号?

'short?' to 'short' 'short?' to 'short' - Which says: I can not convert a Int16? 'short?' to 'short' -哪说:我不能转换Int16? to an Int16 The question mark defines, that this value can be null . Int16问号定义,该值可以为null

So if you change your model, you do not need to parse anything, but you need to use t.EmpNo.Value 因此,如果更改模型,则无需解析任何内容,但需要使用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. EmpNo可能永远不会为空,而您的一个EmpNo在数据库中可以为空,而另一个则不能为空。 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. 如果由于某种原因它们有时应该可以为Null,则它们在数据库中都必须为可为空。 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? 您可能需要更改公共Int16吗? LocalAmount { get; LocalAmount {get; set; 组; } back to public Int16 LocalAmount { get; }返回公共Int16 LocalAmount {get; set; 组; }. }。

Essentially: Empno must be non nullable everywhere or nullable everywhere. 本质上:Empno必须在任何地方都不能为null或在任何地方都不能为null。 In the database and the code. 在数据库和代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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