Dynamic versus static ViewModels When returning ViewModels from the server-side to client apps, you can think about those
ViewModels as DTOs (Data Transfer Objects) that can be different to the internal domain entities of
your entity model because the ViewModels hold the data the way the client app needs. Therefore, in
many cases, you can aggregate data coming from multiple domain entities and compose the
ViewModels precisely according to how the client app needs that data.
Those ViewModels or DTOs can be defined explicitly (as data holder classes), like the
OrderSummary
class shown in a later code snippet. Or, you could just return dynamic ViewModels or dynamic DTOs
based on the attributes returned by your queries as a dynamic type.
ViewModel as dynamic type As shown in the following code, a
ViewModel
can be directly returned by the queries by just returning
a
dynamic type that internally is based on the attributes returned by a query. That means that the
subset of attributes to be returned is based on the query itself. Therefore, if you add a new column to
the query or join, that data is dynamically added to the returned
ViewModel
.
using Dapper;
using Microsoft.
Extensions
.
Configuration
;
using System.
Data
.
SqlClient
;
using System.
Threading
.
Tasks
;
using System.
Dynamic
;
using System.
Collections
.
Generic
;
public class OrderQueries : IOrderQueries
{
public async Task>
GetOrdersAsync
()
{
using (
var
connection =
new SqlConnection
(_connectionString))
{
connection.
Open
();