Dude Lebowski
Dude Lebowski

Reputation: 159

.NET MVC 3 Search in controller

I'm new to .NET. I'm trying to do something very simple. I would like to perform a search on a Model in my controller and retrieve the first entity returned :

var cercueils = from y in db.Cercueils select y;
cercueils = cercueils.Where(z => z.Type.ToUpper().Contains(dr[13].ToUpper())
          || z.AncienType.ToUpper().Contains(dr[13].ToUpper()));
Cercueil cercueil = cercueils.First();

But this is not good, as it throws an error :

Le type de nœud « ArrayIndex » de l'expression LINQ n'est pas pris en charge dans LINQ to Entities.

(Google translate: "the node type of the LINQ expression arrayIndex n is not supported in LINQ to Entities")

How can I achieve that ?

Thanks for your help.

Upvotes: 1

Views: 956

Answers (3)

Matt Murrell
Matt Murrell

Reputation: 2351

I believe Linq doesn't know how to execute 'dr[13]' in the context of deferred execution... try the following:

var tmp = dr[13].ToUpper();
var cercueils = from y in db.Cercueils select y;
cercueils = cercueils.Where(z => z.Type.ToUpper().Contains(tmp)
          || z.AncienType.ToUpper().Contains(tmp));
Cercueil cercueil = cercueils.FirstOrDefault();

Also, I usually recommend FirstOrDefault with a null check afterwards :)

Upvotes: 3

Andy Stannard
Andy Stannard

Reputation: 1703

        var cercueils = (from y in db.Cercueils
                        where y.blahblah = blahblah
                        select y).FirstOrDefault();

Upvotes: 0

Zruty
Zruty

Reputation: 8687

I think your Where() clause (z => z.Type.ToUpper().Contains(dr[13].ToUpper()) etc.) cannot be translarted into the SQL-type query, so Linq to Entities gives you the aforementioned error.

You can fix the error in twi ways: either transform your expression so that Linq to Entities is able to generate the query (I had some success with IndexOf() instead of Contains()), or just download the entire table and perform the search locally (obviously, the second option will hamper performance):

var cercueils = (from y in db.Cercueils select y).ToList(); // load the entire dataset
cercueils = cercueils.Where(z => z.Type.ToUpper().Contains(dr[13].ToUpper())
      || z.AncienType.ToUpper().Contains(dr[13].ToUpper()));
Cercueil cercueil = cercueils.First();

Upvotes: 0

Related Questions