我正在使用LINQ,而我最初是通过表中的主键搜索的。但是,现在因为我需要通过多个页面传递我的搜索字段(这使得URL非常大)。我想通过改变从页面之间传递Guid到在页面之间传递字符串来解决这个问题。这就是我之前的事情:
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'类型的操作数和'字符串?'
答案 0 :(得分:4)
您发现字符串和可空字符串之间的==
没有运算符重载。
在任何情况下,可以为空的字符串都没有意义,因为普通的旧字符串已经可以为空。将您方法的签名更改为
public ActionResult TechKnowledgebaseList(string createdBy)
它将按预期工作,您仍然可以根据需要将null
或空字符串传递给您的方法。
答案 1 :(得分:1)
默认情况下,无需将string
包裹为Nullable
类型:
public ActionResult TechKnowledgebaseList(string? createdBy)
只需离开?
,您就可以了:
public ActionResult TechKnowledgebaseList(string createdBy)
答案 2 :(得分:-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);
}