Reputation: 1
I am working on a function that returns a film object based on the name of the film passed in.
I am new to linq2entities and I don't know how to resolve the compiler error I am getting.
public Film GetFilm(string FilmName)
{
Film temp = FilmEntity.Films.Where(f => f.FilmTitle == FilmName);
return temp;
}
In this code it feels like f is not defined, but I don't know if that is the case or not.
Upvotes: 0
Views: 28
Reputation: 10191
Where returns a IQueryable of Films however you're assigning it to a single Film.
If you're only expecting one result there are better methods than Where you can use. The common ones I use are
Assuming FilmTitle is unique you should be safe to use Single(), if it isn't then you need to consider what happens if there's more than one with the same title.
public Film GetFilm(string FilmName)
{
Film temp = FilmEntity.Films.Single(f => f.FilmTitle == FilmName);
return temp;
}
An alternative (if you're expecting multiple films) may be
public IEnumerable<Film> FindFilms(string searchString)
{
return FilmEntity.Films.Where(f => f.FilmTitle.Contains(searchString));
}
Upvotes: 0
Reputation: 1911
The problem is that Where doesn't return Film
but an IQueryable<Film>
What you should do is this
public Film GetFilm(string FilmName)
{
Film temp = FilmEntity.Films.Where(f => f.FilmTitle == FilmName).Single();
return temp;
}
or this
public Film GetFilm(string FilmName)
{
Film temp = FilmEntity.Films.Single(f => f.FilmTitle == FilmName);
return temp;
}
This all assuming you only have one with this name in the db. If there might be more you can use First or FirstOrDefault (this one will not return an exception if it doesn't find anything). Same goes for Single. You can also use SingleOrDefault if there might be ONE or NONE
Upvotes: 3