我用它来查询字符串来过滤我在数据库中的电影有问题



string mid=Request.QueryString["ID"];

    if ( db.Movies.Where(i=>i.ID==mid))
    {
        repMovie.DataSource = db.Movies.Find().ToString();
        repMovie.DataBind();
    }

尝试添加.Any()以在if语句中返回布尔值。

如果可枚举对象返回任何结果,则Any()返回true。

if ( db.Movies.Where(i=>i.ID==mid).Any()) 
{    
    //...
}

首先,db.Movies.Where(i=>i.ID==mid)不是布尔值。你为什么要测试它是真是假?

第二,repMovie.DataSource = db.Movies.Find().ToString();是没有条件的,它怎么会返回正确的东西呢?你为什么不这样做:

(假设最多有一场比赛):

var matchingMovie = db.Movies.FirstOrDefault(i => i.ID == movieId);
if (matchingMovie !== null) {
   // you found it in one operation and can work with it now
}

我建议不要使用mid这样的变量名。那是什么?其他人,甚至是你自己,在几个月后看到它,都会不知道,必须做额外的扫描工作来弄清楚它的意义。请改用movieId

既然如此,为什么你自己直接从查询字符串中获取movieId?你的MVC操作方法应该为你做这件事:

public ActionResult Index(int ID) {
   // Lookie! you've automatically gotten the ID from the querystring, and
   // you also know it's a non-null integer. If it were null or a non-integer,
   // it wouldn't match this route and the client would get a 404, unless you
   // had another route to handle those.
}

替代方式

int numMid = Convert.ToInt32(mid);
if ( db.Movies.Where(i=>i.ID==numMid).Count()>0) 
{    
    //...
}

int numMid = Convert.ToInt32(mid);
if (db.Movies.Any(i=>i.ID==numMid)) 
{    
    //...
}

最新更新