haansi
haansi

Reputation: 5730

EF generic repository Query method, how to select one column?

I am usign EF 4 with repository patren which have a generic query method which is coded as below:

 public IEnumerable<T> Query(Expression<Func<T, bool>> filter)
    {
        return objectSet.Where(filter);
    }

I know how to query for selecting a complete object which was like below:

context.PeriodRepository.Query(a => a.EntityId == selectedEntityId);

Can you please guide me how to query not compelte object rather how to get just a property, I want to put property directly into textbox.

thanks

Edit

I have decided to get full object from query as:

MyType obj = context .Signatories1Repository.Query(a=>a.Id==signatory1Id);

but it shows an error:

Cannot convert from IEnumarable to type. An explicit conversion exisit. Are you missing a cast ?

Can you please advice how I can make it workign correctly ?

Upvotes: 0

Views: 2941

Answers (1)

Ivo
Ivo

Reputation: 8352

In order to retrieve just a property (or some properties), you need to call the Select() linq extension method for doing a transformation that will retrieve just what you want:

context.PeriodRepository.Query(a => a.EntityId == selectedEntityId)
       .Select(x => x.TheProperty);

I also suggest returning IQueryable<T> instead of IEnumerable<T> in your Query method. In fact, I would avoid the query method and just make your repository implement IQueryable<T> so you can just use the out-of-the-box linq extension methods like Where() instead.

Upvotes: 2

Related Questions