Hi i try to get some Date from my Database but it wont work and i really have no Idea why.
I get following Error:
Error: Entities in 'DataBase' participate in the 'FK_MSCourse_Language' relationship. 0 related 'Language' were found. 1 'Language' is expected.
My Code:
var language = db.Language.Where(x => x.Designation == publicLanguage);
if (language != null)
{
newCourse.Language = language.SingleOrDefault();
}
else
{
newCourse.Language = db.Language.SingleOrDefault(x => x.Designation == "English");
}
If i do it this way it works, but i want to have it dynamically to Languages from the DataBase.
switch (publicLanguage)
{
case "French":
newCourse.Language = db.Language.SingleOrDefault(x => x.Designation == "French");
break;
default:
newCourse.Language = db.Language.SingleOrDefault(x => x.Designation == "English");
break;
}
Anyone knows what i am doing wrong?
Thanks,
Markus
LINQ’s
Whereoperation returns an IEnumerable, which can never be null, making yourifblock useless. It will always executenewCourse.Language = language.SingleOrDefault();no matter what.I’m also thinking that trying to use
==on what is most likely a string variable could be causing you some problems also. I would recommend using the.Equals()method instead, which will actually investigate if the strings are equal. Also, since you’re just trying to grab the first one, why not just do this:This will grab the first one that matches that language, or return null. In such a case, then you can just have an
ifstatement which will then assign English as the language if thelanguagevariable is, in fact, null.