Linq - Select single Entity

Posts   
 
    
ianvink
User
Posts: 394
Joined: 15-Dec-2006
# Posted on: 12-Oct-2009 15:42:32   

Often I have a simple query, but only want the first item. So I use the Take() linq method.


            var q = (ILLBLGenProQuery) (from t in linq.SoxTestPlan
                                       orderby t.TestYear descending 
                                       where t.OpenPlan==false
                                       select t).Take(1);


However I then have to get the collection and take the first one out


EntityCollection<SoxTestPlanEntity> planEntities = q.Execute<EntityCollection<SoxTestPlanEntity>>();

is there a simpler way to specify the query but just Fetch 1 entity without having to make a collection then get collection[0] ?

Ian

Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 12-Oct-2009 15:59:38   

A single entity is fetched using the PK value. Otherwise your fetching an EntityCollection, even if you need one entity.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39862
Joined: 17-Aug-2003
# Posted on: 12-Oct-2009 16:01:19   

Also take a look at the .FirstOrDefault() method wink

Frans Bouma | Lead developer LLBLGen Pro
ianvink
User
Posts: 394
Joined: 15-Dec-2006
# Posted on: 12-Oct-2009 16:04:02   

Walaa wrote:

A single entity is fetched using the PK value. Otherwise your fetching an EntityCollection, even if you need one entity.

If I have a unique index on a column, say the Email of the "Customer" table which is not the PK, there doesn't seem to be a way to single-entity Fetch with the adapter based on that. Is that correct.

If there was that would be helpful too.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39862
Joined: 17-Aug-2003
# Posted on: 12-Oct-2009 17:57:27   

ianvink wrote:

Walaa wrote:

A single entity is fetched using the PK value. Otherwise your fetching an EntityCollection, even if you need one entity.

If I have a unique index on a column, say the Email of the "Customer" table which is not the PK, there doesn't seem to be a way to single-entity Fetch with the adapter based on that. Is that correct.

If there was that would be helpful too.

Linq is about sets, enumerating sets and obtain data from these sets. So single entities are always fetched by enumerating the overall set with a where filter etc. (inside the db).

So you can use FirstOrDefault on LinqMetaData.Customer with a filter on Email, which will result in a single entity, as just 1 entity matches the query. That it is placed inside a collection internally is not that important, you won't see the collection, only the entity:

var customer = new LinqMetaData(adapter).Customer.FirstOrDefault(c=>c.Email==someEmail);

Frans Bouma | Lead developer LLBLGen Pro
ianvink
User
Posts: 394
Joined: 15-Dec-2006
# Posted on: 12-Oct-2009 17:58:56   

Perfect! Thanks!