Below is a Linq query I’m using in one of my ASP MVC controllers. I am attempting to pull one record from an SQL database, and then compare it with the user’s input. If the state code the user entered does not match the state code associated with the product code the user has entered, it will kick back an error message.
I’m stuck, though, on how to access the StateCode field from the “course” variable. Using Visual Studio I can step through the code and see the value in there (while examining via the Locals window/readout), however I do not know how to get the value I’m looking for.
This is my first time using Linq, so any and all help/suggestions will be greatly appreciated. Thanks!
var course = from c in db.AgentContEd
where c.CourseCode == agentconted.CourseCode
select c;
if (agentconted.StateCode.Equals(course.StateCode))
{
db.AgentContEd.Add(agentconted);
db.SaveChanges();
return RedirectToAction("Details", "Agent", new { id = agentconted.SymetraNumber });
}
else
{
ViewBag.ErrorMessaeg = "State code must match Product Training state code";
}
You are pulling back an
IQueryable<T>when you instead need a single entity. If your query produces no resulting record, course will be set to null. A query that returns more than 1 record will throw an exception.