简体   繁体   中英

How can I make Entity Framework map a DbDataReader?

I'm trying to make Entity Framework return multiple results for custom queries then have it map back to Entity Framework Code First models. Is it possible to use the internal mapping engine of Entity Framework?

I can guarantee that the rows returned by both queries in the result sets map directly to an EF model. As an internal requirement, I can't use a stored procedure.

public void MultipleResultSets()
{
    var db = new DbContext();
    var command = db.Database.Connection.CreateCommand();
    command.Connection.Open();
    command.CommandText =
        @"
        SELECT * FROM TableA; 
        SELECT * FROM TableB;
        ";

    using (var reader = command.ExecuteReader())
    {
        // Map Table A rows
        var tableARows = new List<TableARow>();
        while (reader.Read())
            tableARows.Add(reader.Map<TablARow>()); // "Map()" is not real

        reader.NextResult();

        // Map Table B rows
        var tableBRows = new List<TableBRow>();
        while (reader.Read())
            tableARows.Add(reader.Map<TablBRow>()); // "Map()" is not real
    }
    command.Connection.Close();
}

Disclaimer : I'm the owner of the project EF+ .

Here is an extension method you can find from my repository which uses the internal mapping engine for mapping a data reader.

public static IEnumerable<T> MapReader<T>(this DbContext context, DbDataReader reader) where T : class
{
    return ((IObjectContextAdapter) context).ObjectContext.Translate<T>(reader);    
}

You can then use your code like this:

public void MultipleResultSets()
{
    var db = new DbContext();
    var command = db.Database.Connection.CreateCommand();
    command.Connection.Open();
    command.CommandText =
        @"
        SELECT * FROM TableA; 
        SELECT * FROM TableB;
        ";

    using (var reader = command.ExecuteReader())
    {
        // Map Table A rows
        var tableARows = db.MapReader<TableA>(reader);

        reader.NextResult();

        // Map Table B rows
        var tableBRows = db.MapReader<TableB>(reader);
    }
    command.Connection.Close();
}

Note : The extension method has been updated to use Pawel answer "ObjectContext.Translate"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM