Reputation: 40162
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();
}
Upvotes: 0
Views: 701
Reputation: 11327
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"
Upvotes: 2