Why doesn't Select () convert IEnumerable <dynamic> to IEnumerable <StrongType>?

I'm trying to use Dapper just to map database tables to types in C #, however some of my types need extra elements that aren't in the table. To do this, I use a factory that can take column values ​​and set the appropriate properties.

public IEnumerable<IMyType> All() {
  var query = _connection.Query("SELECT * FROM [table]");
  return query.Select(o => _myTypeFactory.Create(o));
}

Currently, this leads to a return statement that generates an error:

Cannot convert expression type 'System.Collections.Generic.IEnumerable<dynamic>'to return type'System.Collections.Generic.IEnumerable<IMyType>'

My factory class looks something like this:

public class MyTypeFactory {
  public IMyType Create(dynamic o) {
    return Create((String) o.Code, (Int32) o.KeyID);
  }
  public IMyType Create(String code, Int32 keyID) {
    return new MyType(code, Cache.Lookup(keyID));
  }
}

Why Select()does the method not return IEnumerable<IMyType>? What do I need to do to make this work? Is this just the wrong approach and is there a better way?

+5
2

Cast<> LINQ:

public IEnumerable<IMyType> All() {
  var query = _connection.Query("SELECT * FROM [table]");
  return query.Select(o => _myTypeFactory.Create(o))
              .Cast<IMyType>();
}

:

public IEnumerable<IMyType> All() {
  var query = _connection.Query("SELECT * FROM [table]");
  return query.Select(o => (IMyType) _myTypeFactory.Create(o));
}

, IEnumerable<dynamic> IEnumerable<IMyType> . IEnumerable<dynamic> , , , IEnumerable<IMyType>.

, , , _myTypeFactory.Create(o) - , .. dynamic. Select - IEnumerable<dynamic>.

- generic type Select.

public IEnumerable<IMyType> All() {
  var query = _connection.Query("SELECT * FROM [table]");
  return query.Select<IMyType>(o => _myTypeFactory.Create(o));
}

- Func<dynamic, IMyType> - , ...

EDIT: , . , .

+9

, , select, IEnumerable<IMyType>.

public IEnumerable<IMyType> All() {
  var query = _connection.Query("SELECT * FROM [table]");
  return query.Select(o => _myTypeFactory.Create((Object)o)); //cast dynamic type to Object
}

public IEnumerable<IMyType> All() {
      IEnumerable<object> query = _connection.Query("SELECT * FROM [table]"); //IEnumerable<dynamic> is the same as IEnumerable<object>
      return query.Select(o => _myTypeFactory.Create(o)); 
}
+1

All Articles