2015-11-03 60 views
1

我正在使用LINQ,并且我最初是通过表中的主键搜索的。但是,现在我需要将我的搜索字段传递给大量页面(这使得URL非常大)。我想通过从页面之间传递Guid到在页面之间传递字符串来解决此问题。这是什么之前,我有:如何在LINQ中使用字符串进行查询

public ActionResult TechKnowledgebaseList(Guid? createdById) 
{ 
    var model = db.Knowledgebases.AsQueryable(); 

    if (createdById != null & createdById != Guid.Empty) 
    { 
      model = model.Where(k => k.CreatedById == createdById); 
      ViewBag.CreatedBy = db.Users.Where(c => c.UserId == createdById).First().FullName; 
      ViewBag.CreatedById = createdById; 
    } 
    model = model.OrderBy(k => k.CreatedDate); 
    var result = model.ToList(); 

    return View(result); 
} 

这里是我想现在要做的:

public ActionResult TechKnowledgebaseList(string? createdBy) 
{ 
    var model = db.Knowledgebases.AsQueryable(); 

    if (createdBy != null) 
    { 
      model = model.Where(c => c.CreatedBy.FullName == createdBy); 
      ViewBag.CreatedBy = db.Users.Where(c => c.UserName == createdBy).First().FullName; 
      ViewBag.CreatedBy = createdBy; 
    } 
    model = model.OrderBy(k => k.CreatedDate); 
    var result = model.ToList(); 

    return View(result); 
} 

正如你可以看到我传递一个刺现在(可以为空)。不过,我得到的错误:

Operator '==' cannot be applied to operands of type 'string' and 'string?'

+3

'string?'没有意义,因为它是一个引用类型。只要把''离开。 –

+3

'串? createdBy'编译? –

+0

@Thomas是的,我没有得到该行的错误。 – djblois

回答

4

你已经发现,有一个字符串,可为空字符串之间==没有运算符重载。

在任何情况下,可以为null的字符串都没有意义,因为普通的旧字符串已经可以为空。你的方法的签名更改为

public ActionResult TechKnowledgebaseList(string createdBy) 

而且它会如预期所有的工作,你仍然可以通过null或一个空字符串,以你的方法适当。

1

没有必要包装stringNullable类型,因为它默认为:

public ActionResult TechKnowledgebaseList(string? createdBy) 

只需将?出来,你的罚款:

public ActionResult TechKnowledgebaseList(string createdBy) 
-1

我想c.UserId是字符串?检查字符串时,应该使用string.IsNullOrEmpty(字符串值)。不要在字符串上使用“==”,使用

public ActionResult TechKnowledgebaseList(Guid? createdBy) 
{ 
    string crBy = Guid.GetValueOrDefault(/*some default value or nothing*/).ToString(); 

    var model = db.Knowledgebases.AsQueryable(); 

    if (!string.IsNullOrEmpty(crBy))) 
    { 
      model = model.Where(c => c.CreatedBy.FullName == createdBy); 
      ViewBag.CreatedBy = db.Users.Where(c => c.UserName.Equals(crBy)).First().FullName; 
      ViewBag.CreatedBy = createdBy; 
    } 
    model = model.OrderBy(k => k.CreatedDate); 
    var result = model.ToList(); 

    return View(result); 
}