Customize materialization process in an entity framework provider

我的梦境 提交于 2020-01-15 12:29:07

问题


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:

  1. EF calls the EF provider with an expression tree

  2. The provider returns a sql query

  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!