public class Note {}
public class NoteViewModel : Note {}
public class NoteDTO : Note {}
dbContext.Set<Note>().Select(note => new NoteViewModel {
prop1 = note.prop1,
prop2 = note.prop2,
...
}).ToArray();
// or
dbContext.Set<Note>().Select(note => new NoteDTO {
prop1 = note.prop1,
prop2 = note.prop2,
...
}).ToArray();
I'm not sure EF Core will instantiate the Note
object before instantiate and copy/deserialize the data into NoteViewModel
object or not, but I believe it's not.
- Is there a way to "shortcut" the
Select
action above? Imagine if theNote
has a lot of columns. Perhaps something likeSelectAs<NoteViewModel>()
- I looking for a way to downcast the configured entity type to any derived type regardless configured with EF Core or not without instantiate the entity type.
Thanks
public class Note {}
public class NoteViewModel : Note {}
public class NoteDTO : Note {}
dbContext.Set<Note>().Select(note => new NoteViewModel {
prop1 = note.prop1,
prop2 = note.prop2,
...
}).ToArray();
// or
dbContext.Set<Note>().Select(note => new NoteDTO {
prop1 = note.prop1,
prop2 = note.prop2,
...
}).ToArray();
I'm not sure EF Core will instantiate the Note
object before instantiate and copy/deserialize the data into NoteViewModel
object or not, but I believe it's not.
- Is there a way to "shortcut" the
Select
action above? Imagine if theNote
has a lot of columns. Perhaps something likeSelectAs<NoteViewModel>()
- I looking for a way to downcast the configured entity type to any derived type regardless configured with EF Core or not without instantiate the entity type.
Thanks
Share Improve this question edited Mar 15 at 13:16 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Mar 15 at 11:10 codetalecodetale 1017 bronze badges 3 |1 Answer
Reset to default 3Select
is a projection so when you use:
dbContext.Set<Note>().Select(note => new NoteViewModel {
Id = note.Id,
prop1 = note.prop1,
prop2 = note.prop2,
}).ToArray();
... as an example, even if Note has 30 columns, the resulting SQL would just involve SELECT Id, prop1, prop2 FROM Notes
. It does not fetch all columns. This also applies to when you use a navigation property. If Note has a navigation property to a related table and you use Select()
to access one column from that related entity, EF will join the tables, but only return that single specified column.
Mapping libraries like Automapper, Mapify, and Mapperly have IQueryable
projection methods that work in the same way, giving you something like what you described with SelectTo<T>
. With Automapper there is ProjectTo<NoteViewModel>(config)
This takes a mapper configuration argument with any mappings that cannot be formed via convention.
ProjectTo()
method. – Progman Commented Mar 15 at 11:16