Search code examples
selectsimple.data

Simple.Data Select specific columns


I have a call made to Simple.Data where I want to limit the columns that are being brought back. However I am hitting problems..

This works fine:

var db = Database.Open();

var questionIdRow = db.Question.FindByFriendlyId(friendlyId);

if (questionIdRow == null) return Guid.Empty;

return questionIdRow.QuestionId;

However, the following doesn't work (I get a Simple.Data.UnresolvableObjectException 'Column not found')

var db = Database.Open();

var questionIdRow = db.Question.FindByFriendlyId(friendlyId)
                               .Select(db.Question.QuestionId);

if (questionIdRow == null) return Guid.Empty;

return questionIdRow.QuestionId;

I was under the impression from the Simple.Data documentation that this was all that I needed to do to limit the selected columns. Note that the selection is simply selecting the same column that is referenced later on.

The actual exception is thrown on the var questionIdRow = line.

Can anybody give me some guidance?


Solution

  • this is a common problem, and has actually led to FindBy being deprecated before we even get to 1.0. The problem is that FindBy returns a record straight away, so you can't continue to call query methods on it.

    The correct approach is to call FindAllBy and end with a First or FirstOrDefault:

    var db = Database.Open();
    
    var questionIdRow = db.Question.FindAllByFriendlyId(friendlyId)
                               .Select(db.Question.QuestionId)
                               .FirstOrDefault();
    
    if (questionIdRow == null) return Guid.Empty;
    
    return questionIdRow.QuestionId;