4

Need some help creating a generic method for selecting fields by their name.

something like this:

T GetDocField<T>(string doc_Id, string fieldName)

The best I got is using projection which gives me the doc with only the wanted field seted:

 public T GetDocField<T>(string Doc_Id, string fieldName)
 {
    var value = DocCollection.Find(d => d.Id == Doc_Id)
               .Project<T>(Builders<Doc>.Projection
               .Include(new StringFieldDefinition<Doc>
               (fieldName))).FirstOrDefaultAsync().Result;

note: I'm using the new c# driver (2.0)

Thanks!!

rnofenko
  • 9,198
  • 2
  • 46
  • 56
  • If it's generic then why select by name and not by expression? – i3arnon Jun 30 '15 at 16:55
  • I have posted a new question about sub field selection. for the googlers out there: http://stackoverflow.com/questions/31161104/mongodb-c-sharp-select-specific-field-dot-notation –  Jul 01 '15 at 13:10

1 Answers1

9

You can do next:

public async Task<TValue> GetFieldValue<TEntity, TValue>(string id, Expression<Func<TEntity, TValue>> fieldExpression) where TEntity : IEntity
{
    var propertyValue = await collection
        .Find(d => d.Id == id)
        .Project(new ProjectionDefinitionBuilder<TEntity>().Expression(fieldExpression))
        .FirstOrDefaultAsync();

    return propertyValue;
}

and call it

var value = await GetFieldValue<Item, string>("111", x => x.Name);
rnofenko
  • 9,198
  • 2
  • 46
  • 56
  • This works perfect, but i wanted to go a little forward with this solution. I added an edit for the question , thanks again ! –  Jul 01 '15 at 09:10
  • 2
    @AviPinhas It's considered bad practice here on SO to [append a new issue to an existing question](http://meta.stackoverflow.com/questions/296489/). Please edit out that second issue and post it in a new question. Again, would be great for you and the SO community to accept the answer above if you found it useful but there is no obligation in doing so. – chridam Jul 01 '15 at 10:50
  • I have posted a new question for sub field selection. for googlers who are interested: http://stackoverflow.com/questions/31161104/mongodb-c-sharp-select-specific-field-dot-notation –  Jul 01 '15 at 13:08