无法隐式转换类型'int?'到"int"-在控制器或查看页面上

无法隐式转换类型'int?'到

问题描述:

在执行以下代码时,我的控制器中出现此错误:

While executing below code, I got this error in my Controller:

无法隐式转换类型'int?'到"int".存在显式转换(您是否缺少演员表?)

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

我的控制器中的 t.TOT_QTY 出现错误.

Error comes on t.TOT_QTY in my controller.

控制器:

dcms = (from t in db.ASN_ITEM
                    ...
                    where
                      (t.TOT_QTY - t.SCND_QTY) != 0  
                    select new ASNVarianceRep
                    {                           
                        TOT_QTY = t.TOT_QTY,
                        SCND_QTY = t.SCND_QTY,
                        VAR_QTY = (t.SCND_QTY - t.TOT_QTY)                            
                    }).Distinct();   

数据库中 t.TOT_QTY 的类型为 int?.但是变量 TOT_QTY 只是Model类上的 int .

Where t.TOT_QTY is of type int? in the database. But the variable TOT_QTY is just an int on Model class.

型号:

public class ASNVarianceRep : ASN_ITEM
{  
    public int TOT_QTY { get; set; }
    ...
 } 

如果我更改了 public int TOT_QTY {get;放;} 更改为 public Nullable< int>TOT_QTY {get;放;} ,然后将解决控制器中的错误.但是,视图页面的第 itotqty = itotqty + item.TOT_QTY;

If I changed public int TOT_QTY { get; set; } to public Nullable<int> TOT_QTY { get; set; }, Then error in the controller will be solved. But same error will be there on view page at line itotqty = itotqty + item.TOT_QTY;

查看:

 @if (Model != null)
    {
        var itotqty = 0;
        foreach (var item in Model)
        {
            itotqty = itotqty + item.TOT_QTY;                
        <tr>                
            <td>
                @Html.DisplayFor(modelItem => item.TOT_QTY)
            </td>
            ...
        </tr>
        }
        <tr>                
            <td style="text-align: center"><b>@itotqty.ToString() </b></td>                
        </tr>

所以,我想要的是我需要将 t.TOT_QTY 的类型从 int吗?转换为Controller中的 int 还是 var itotqty = 0; 从查看页面上的 int int?.怎么做?

So, what I want is either I need to make the type of t.TOT_QTY from int? To int in Controller or make var itotqty = 0; from int to int? on view page. How to do so?

分配给模型时,可以在查询中显式转换为 int .目前,它正在尝试将隐式强制转换为失败.

You can explicitly cast to an int in your query when assigning to your model. Currently it is trying to do an implicit cast as failing.

dcms = (from t in db.ASN_ITEM
       ...
       where
           (t.TOT_QTY - t.SCND_QTY) != 0  
           select new ASNVarianceRep
           {                           
               TOT_QTY = (int)t.TOT_QTY,
               SCND_QTY = t.SCND_QTY,
               VAR_QTY = (t.SCND_QTY - t.TOT_QTY)                            
           }).Distinct();   

请参阅此MSDN页面以获取有关显式强制转换的更多信息: https://msdn.microsoft.com/en-us/library/ms173105.aspx

See this MSDN page for more info on explicit casting: https://msdn.microsoft.com/en-us/library/ms173105.aspx