问题
I have a problem with booleans returned by an entity framework provider I'm writing. The EF expecting a boolean while the ADO provider returns an Int16 so the EF raises an InvalidOperationException The specified cast from a materialized 'System.Int16' type to the 'System.Boolean' type is not valid. Is there a way to customize the materialization process of the entity framework to make it call a materialization process implemented by the provider?
EDIT
Partially found a solution... I can't find a way to change materialization behaviour but I changed the DbDataReader behaviour in this way
public override bool GetBoolean(int ordinal)
{
object booleanObject = GetValue(ordinal);
if (booleanObject == null)
throw new InvalidOperationException("Cannot cast null to boolean");
if (booleanObject.GetType() == typeof(bool))
return _wrappedDataReader.GetBoolean(ordinal);
else if (booleanObject.GetType() == typeof(short))
return ((short)booleanObject) != 0;
else
throw new InvalidOperationException(string.Format("Cannot convert {0} to boolean", booleanObject.GetType()));
}
EDIT Some more explanations...
I'm writing an EF provider.
EF (about reading from db) works in this way:
EF calls the EF provider with an expression tree
The provider returns a sql query
The EF runs the query The EF materializes the query results
In expression tree the EF providers knows the return type that should be a boolean but there is no way to cast it to boolean in the query.
The only way to cast the Int16 to the Boolean is during the materialization process or in the DBDataReader (inserting something like ((Int16)value) != 0)
Actually I solved it writing a wrapper on the DbDataReader (several empty overrides and one override with the conversion) but probably I'm missing something in the materialization process.
来源:https://stackoverflow.com/questions/27100219/customize-materialization-process-in-an-entity-framework-provider