Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Query Projection mean in Entity Framework?

Tags:

I am looking at some EF examples and trying to decipher what 'Query Projection' exactly equates to when doing LINQ to Entities or EntitySQL. I believe it is when the query results are filtered and projected into an anonymous type but not 100% sure.

Can someone please define this and maybe provide a small L2E query that uses an example of it?

like image 331
atconway Avatar asked Jun 01 '12 21:06

atconway


People also ask

What is the use of projection queries in Entity Framework?

Projection queries improve the efficiency of your application, by only retrieving specific fields from your database. Once you have the data, you may want to project or filter it as needed to shape the data prior to output. The main task of any LINQ to Entities expression is to obtain data and provide it as output.

What is query projection?

Projection queries allow you to query Datastore for just those specific properties of an entity that you actually need, at lower latency and cost than retrieving the entire entity. Projection queries are similar to SQL queries of the form: SELECT name, email, phone FROM CUSTOMER.

What is entity projection?

Entity Framework Projection A projection is just a way of mapping one set of properties to another. In Entity Framework, it's a way of translating a full entity (database table) into a C# class with a subset of those properties.

How do you write a projection query?

Projection means choosing which columns (or expressions) the query shall return. Selection means which rows are to be returned. select a, b, c from foobar where x=3; then "a, b, c" is the projection part, "where x=3" the selection part.


1 Answers

Projection is when the result of a query is output to a different type than the one queried. Another article defined it as : the process of transforming the results of a query

Projection can be to an anonymous type, but could also be to a concrete type. If you come from a SQL world, it is akin to the columns listed in your SELECT clause.

Example selecting a sub-set of an object into an concrete type:

ParentObj.Select(x=> new ParentSlim { ParentID = x.ParentID,  Name = x.Name } ); 

.
Example merging to object into a 3rd anonymous type:
Note: the select new portion is the projection.

from P in ParentObj.AsQueryable() join C in ChildObj.AsQueryable() on P.ParentID == C.ParentID  select new {                              // <-- look ma, i'm projecting!                ParentID = P.ParentID,                Name     = P.Name,                SubName  = C.Name                RandomDate = DateTime.UtcNow()          } 
like image 69
EBarr Avatar answered Oct 12 '22 20:10

EBarr