Question

I'm very familiar with returning a Entity from my model using CreateQuery<T> but how do I return results from multiple tables? I have gotten close by using CreateQuery<dynamic> but this seems to return a System.Data.Entity.Core.Objects.MaterializedDataRecord Object, which I cannot work with.

var sql = "SELECT TableA.ColumnA, TableB.ColumnB
 FROM TestingContext.TableA
LEFT OUTER JOIN TestingContext.TableB
ON TableA.TableBId = TableB.Id";

var results = ((IObjectContextAdapter)context).ObjectContext.CreateQuery<dynamic>(sql);
Était-ce utile?

La solution

For that you need to use the DbDataRecord and then map it to some object (a DTO, or the dynamic object). There is an example of how to do that here: http://www.codeproject.com/Articles/152742/EF-DbDataRecord-ConvertTo .

The problem with this kind of access on the ORM is that it breaks the abstraction provided by it. Then you can't use the Mapper provided by the CreateQuery because the object you are using is not in the model.

You can see here Entity Framework + AutoMapper ( Entity to DTO and DTO to Entity ) some examples on how to use the Mapper.

I suggest that you use Linq because it can create anonymous types. And for that join you don't need to manually create SQL, it is not so complex. Entity framework left join

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top