I am using LINQ and I was Originally searching by the Primary Key in the table. However, now since I need to pass the my search fields through numerous pages (which makes the URL very large). I want to fix this by changing from passing Guids between pages to passing the Strings between pages. This is what I had prior:
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);
}
Here is what I am trying to do now:
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);
}
As you can see I am passing in a sting now (that can be empty). However, I am getting the error:
Operator '==' cannot be applied to operands of type 'string' and 'string?'
You have discovered that there is no operator overload for ==
between a string and a nullable string.
In any case, a nullable string makes no sense, as a plain old string is already nullable. Change your method's signature to
public ActionResult TechKnowledgebaseList(string createdBy)
And it will all work as expected, you can still pass null
or an empty string to your method as appropriate.
There's no need to wrap string
as Nullable
type, as it is by default:
public ActionResult TechKnowledgebaseList(string? createdBy)
Simply leave the ?
out and you're fine:
public ActionResult TechKnowledgebaseList(string createdBy)
I suppose c.UserId is string? When checking string, you should use string.IsNullOrEmpty(string value). Don't use "==" on strings, use
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.