c# - How to include complex entity fields in a projected entity framework object? -
i use system.data.entity.dbextensions
include()
method cause complex entity fields included in query results repositories. however, when project entities new classes, seem lose "concretization" of included complex entity fields. example, wanted return event
object repo, , able access complex entity field assessment
:
public class eventrepository { ... public ilist<event> getevents() { using (var context = new mydatabasecontext()) { return context.events .include(evnt => evnt.actualassessment) .tolist(); } } ... }
i can run following code without hitch because of include
used above:
var repoevents = new eventrepository(); var events = repoevents.getevents(); console.writeline(events[0].actualassessment.assessmentdate.tostring());
but want project event
s wrapper object extendedevent
info, this:
public class eventrepository { ... public ilist<extendedevent> getextendedevents() { using (var context = new mydatabasecontext()) { return context.events .include(evnt => evnt.actualassessment) .select(evnt => new { theevent = evnt, someextradata = 123 }) .tolist() .select(evntinfo => { return new extendedevent { theevent = evntinfo.theevent, someextradata = evntinfo.someextradata }; }) .tolist(); } } ... }
i try , run code:
var repoevents = new eventrepository(); var extendedevents = repoevents.getextendedevents(); console.writeline(extendedevents[0].theevent.actualassessment.assessmentdate.tostring());
this gives me error "the objectcontext instance has been disposed , can no longer used operations require connection." - actualassessment
has not been eager-loaded despite use of include
, apparently because projected new wrapper object. how can cause actualassessment
included?
yes, include
ignored in projections. can try make related navigation property part of projection anonymous object:
public ilist<extendedevent> getextendedevents() { using (var context = new mydatabasecontext()) { return context.events .select(evnt => new { theevent = evnt, someextradata = 123, actualassessment = evnt.actualassessment }) .tolist() .select(evntinfo => { return new extendedevent { theevent = evntinfo.theevent, someextradata = evntinfo.someextradata }; }) .tolist(); } }
the actualassessment
attached context , automatic relationship fixup popolate theevent.actualassessment
if
- you don't disable change tracking
- the relationship not many-to-many
as side note: can use asenumerable()
instead of first tolist()
avoid unnecessary overhead of creating list of anonymous objects.
edit
for many-to-many relationship or in case of disabled change tracking must set navigation property after db query materialized, example:
.select(evntinfo => { evntinfo.theevent.actualassessment = evntinfo.actualassessment; return new extendedevent { theevent = evntinfo.theevent, someextradata = evntinfo.someextradata }; })
Comments
Post a Comment