Friday, August 26, 2011

How to retrieve specific columns in Entity Framework

There are some cases that we do not want to retrieve all columns and we only need to grab some columns. Anonymous and dynamic types help to do that.
 var q = from c in context.Set<Content>()
         where c.CatalogId == "ABC"
         select new { c.ContentId, c.ContentName };

OR


IEnumerable<dynamic> q = context.Contents.Where(c => c.CatalogId == "ABC")
                .Select(c => new {c.ContentId, c.ContentName});


//By looking at the sql generated by this query q.ToString() we can see 

SELECT 
[Extent1].[ContentId] AS [ContentId], 
[Extent1].[ContentName] AS [ContentName]
FROM [dbo].[Content] AS [Extent1]
WHERE N'ABC' = [Extent1].[CatalogId]

public IEnumerable<dynamic> Get<T>(DbContext context,
                                   Expression<Func<T, bool>> exp,
                                   Expression<Func<T, dynamic>> columns) where T : class
{
   return context.Set<T>().Where<T>(exp).Select<T, dynamic>(columns);
}


0 comments:

Post a Comment