user3679864
user3679864

Reputation: 1

new to linq. compiler doesnt like my query. Code provided

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

Answers (2)

Liath
Liath

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

  • First (takes the first of a collection, throws if there aren't any)
  • FirstOrDefault (takes the first and returns null if there aren't any)
  • Single (returns one if there is only one, otherwise it will throw)
  • SingleOrDefault (if there's more than one returns null).

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

Ivan Crojach Karačić
Ivan Crojach Karačić

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

Related Questions