麻烦在里面SQL精简查询和MVC3项目空检查 [英] Trouble with checking for null in a SQL Compact query inside and MVC3 project

查看:129
本文介绍了麻烦在里面SQL精简查询和MVC3项目空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过SportsStore例如,从临ASP.NET MVC框架3 工作。在第8章的开头我责成我编辑我ProductController的类,增加了一行。凡如下:

I'm working through the SportsStore example from Pro ASP.NET MVC 3 Framework. At the beginning of chapter 8 i'm instructed to edit my ProductController class, adding the .Where line as follows:

    public ViewResult List(string category, int page = 1)
    {
        ProductsListViewModel viewModel = new ProductsListViewModel
        {
            Products = repository.Products
                .Where(p => category == null || p.Category == category)
                .OrderBy(p => p.ProductID)
                .Skip((page - 1) * PageSize)
                .Take(PageSize),
            PagingInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = repository.Products.Count()
            },
            CurrentCategory = category
        };
        return View(viewModel);
    }

当我运行code我得到以下错误:

When I run the code i get the following error:

Exception Details: System.Data.SqlServerCe.SqlCeException: The specified argument
value for the function is not valid. [ Argument # = 1,Name of
function(if known) = isnull ]

在以下code座在foreach行:

on the foreach line in the following code block:

@model SportsStore.WebUI.Models.ProductsListViewModel

@{
    ViewBag.Title = "Products";
}

@foreach (var p in Model.Products)
{
    Html.RenderPartial("ProductSummary", p);
}
<div class="pager">
    @Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
</div>

我已经搜索好位,发现有很多引用这一点StackOverflow的帖子在多个地方,但改变查询

I've searched a good bit and found a lot of references to this StackOverflow post in multiple places, but changing the query to

.Where(p => category == null ? true : p.Category == category)

是没有效果的。

一些基本信息:


  • 这是使用Razer的视图引擎和C#的MVC3项目。

  • 在我的SQL精简4.0数据库的项目有一个类别。

  • 注释掉类别== NULL位使code运行就好了。

  • 我上面给的第二个版本是在从他们的网站下载的源$ C ​​$ C。

它的工作没有空检查,但我担心如果我只是对我此举可能以后遇到问题。没有人有任何想法,我怎么能解决这个问题?

It does work without the null checking, but i'm worried that if I just move on i may run into issues later on. Does anyone have any ideas as to how I can fix it?

推荐答案

我觉得问题是,LINQ查询被推迟,直到它到达SQL服务器。我的猜测是,SQL服务器紧凑与检查问题类别== NULL

I think the problem is that the LINQ query is being deferred until it gets to the SQL server. My guess is that the SQL compact server has an issue with checking category == null.

尝试使用非递延LINQ方法调用Where方法之前。类似

Try using a non-deferred LINQ method before calling the Where method. Something like

Products = repository.Products.ToList()
    .Where(p => category == null || p.Category == category)
    .OrderBy(p => p.ProductID)
    .Skip((page - 1) * PageSize)
    .Take(PageSize);

这篇关于麻烦在里面SQL精简查询和MVC3项目空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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