As Maciej pointed out in his comment, your issue is most likely the following:
private String education;
public String Education
{
get { return education; }
}
public List<Cours> CreateCrazy()
{
using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
{
if(education==null)
{
education = "";
}
}
}
My best guess is that it doesn't work because however you are normally testing it
education
isn't being set so it is
null
which gets defaulted to
""
inside
CreateCrazy
. When you replace
education
with a hard-coded string it works because there's nothing technically wrong with the LINQ query. It's most likely a problem in your binding.
Additional Thoughts:
Properties: Always set the default on a property or field if needed instead of defaulting inside a method. This keeps variable state consistent. As the code is written now there are two default states depending on whether
CreateCrazy
has been called -
null
and
""
.
Functions: If possible it's good practice to try to maintain a single exit-point for functions. It makes the code easier to read, follow, and therefore maintain. This ties into another good practice in my opinion - eliminate as much
null
reliance as possible. If you call a function that queries and returns a results array, wouldn't you expect "no results" to just be an empty array? This also allows the consuming code to be simplified. Instead of having to
null
check you can simply iterate. If there are no results the loop will just exit immediately.
LINQ: Way too many
ToList
calls.
ToList
forces an evaluation of the LINQ expression so never
ToList
a query for results unless finished with it. Both calls could be removed from the query and just leave the
ToList
on the return value. Also the second part of the query isn't necessary. You're capturing
courseName
into an anonymous object and then transferring that data into a typed object in another select statement. Type it the first time.
Modified with suggestions:
private String education = string.Empty;
public String Education
{
get { return education; }
set
{
if (education != value)
{
education = value;
NotifyOnPropertyChange("Education");
}
}
}
public List<Course> CreateCrazy()
{
List<Course> courseResult = new List<Course>();
using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
{
try
{
var query = from data in db.Courses
where data.education == Education
select new Course {
CourseName = data.courseName
};
courseResult.AddRange(query);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return courseResult;
}