繁体   English   中英

如何在LINQ中使用字符串查询

[英]How to query using a string in LINQ

我正在使用LINQ,最初是按表中的主键进行搜索的。 但是,由于我现在需要将搜索字段传递到许多页面中(这使得URL非常大)。 我想通过将页面之间的Guid更改为页面之间的Strings来解决此问题。 这是我以前的经验:

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);
}

如您所见,我现在正在传递刺痛(可以是空的)。 但是,我得到了错误:

运算符'=='不能应用于类型为'string'和'string?'的操作数

您已经发现,在字符串和可为空的字符串之间没有==运算符重载。

无论如何,可为空的字符串是没有意义的,因为普通的旧字符串已经可以为空。 将方法的签名更改为

public ActionResult TechKnowledgebaseList(string createdBy)

一切都会按预期进行,您仍然可以根据需要将null或空字符串传递给您的方法。

不需要将string包装为Nullable类型,因为默认情况下是这样的:

public ActionResult TechKnowledgebaseList(string? createdBy)

只需离开? 出去,你很好:

public ActionResult TechKnowledgebaseList(string createdBy)

我想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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM