有什么理由为什么我的变量总是为空?在我的MVC项目中 [英] Is there any reason why my variable is always null? in my MVC project

查看:89
本文介绍了有什么理由为什么我的变量总是为空?在我的MVC项目中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我的控制器里有这样的方法...



在我的控制器中,我收到一个id和引擎值作为参数,我正在使用这些来过滤数据。出于某种原因,即使我的数据库中有数据,turbo变量也始终为null。我不知道为什么会这样......我可能会遗漏任何东西吗?:?





  public  ActionResult Vehicle( int ?id, decimal ?engine)
{



var turbo =
_catalogue。 Data.Where(x = > x.manufacturerId == id&& x.EngineLitreCapacity == engine)
.Select(x = > x.Turbo).FirstOrDefault();




var model =
_catalogue.Data.FirstOrDefault(x = < span class =code-keyword>> x.Turbo == turbo);

return PartialView( _Vehicle,model);




}





谢谢

解决方案

首先,是的,这是第一个......



在该方法的第一行放置一个断点。然后运行代码。您的代码将在断点处停止。单击Visual Studio窗口,将鼠标悬停在变量名称id和引擎的顶部。它会告诉你这些变量的值是什么。确保这些值符合您的预期。如果没有,你就是在错误的地方寻找原因。


如果这些值符合你的预期,那么LINQ查询中的WHERE子句就不会做你认为它做的事。


如果 _turbo null ,这意味着表中没有记录,其中 manufacturerId 等于 id 参数和 EngineLitreCapacity 等于引擎参数。


首先将LINQ查询转换为SQL和从SSMS运行它,看看你是否能真正获得给定条件的数据。反之亦然。



这样你可以仔细检查你的结果。



-KR

Hi all,

I have got method like this in my controller ...

in my controller i am receiving an id and and engine values as parameters and thn i am using these to filter the data. For some reason the turbo variable is always null even tho there is data in my database. I'm not sure to why this is .. could i possibly be missing anything?:?


public ActionResult Vehicle( int? id, decimal? engine)
        {



            var turbo =
                _catalogue.Data.Where(x => x.manufacturerId == id && x.EngineLitreCapacity == engine)
                    .Select(x => x.Turbo).FirstOrDefault();
                



            var model =
                _catalogue.Data.FirstOrDefault(x => x.Turbo == turbo);
           
            return PartialView("_Vehicle", model);

          

    
        }



Thank you

解决方案

FIRST, yes, THIS ONE IS FIRST...

Put a breakpoint on the first line in that method. Then run the code. Your code will stop on the breakpoint. Click in the Visual Studio window and hover the mouse on top of the variable names id and engine. It'll tell you what the values of those variables are. Make sure those values are what you expect. If not, you're digging around for a cause in the wrong place.

If those values ARE what you expect, then your WHERE clause in the LINQ query doesn't do what you think it does.


If _turbo is null, that means there is no record in the table where both the manufacturerId is equal to the id parameter and the EngineLitreCapacity is equal to the engine parameter.


First convert your LINQ query to SQL and run it from SSMS, see if you can actually get the data for the given conditions. Or do the vice-versa.

This way you can double check your result.

-KR


这篇关于有什么理由为什么我的变量总是为空?在我的MVC项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆