Skip to content

Instantly share code, notes, and snippets.

Created February 27, 2017 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/907a0fb04a1fa09d63c22830f528fbfb to your computer and use it in GitHub Desktop.
Save anonymous/907a0fb04a1fa09d63c22830f528fbfb to your computer and use it in GitHub Desktop.
public class Sensor
{
public int Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public List<Channel> Channels { get; set; }
}
public class Channel
{
public int Id { get; set; }
public string Name { get; set; }
public List<Reading> Readings { get; set; }
}
public class SensorDTO
{
public int Id { get; set; }
public string Name { get; set; }
public List<ChannelDTO> Channels { get; set; }
}
private Expression<Func<Sensor, SensorDTO>> CreateProjection(IEnumerable<Column> columns)
{
var selectParam = Expression.Parameter(typeof(Sensor), "s");
var row = Expression.New(typeof(SensorDTO));
var bindings = new List<MemberAssignment>();
foreach (var column in columns)
{
Expression body = selectParam;
var destProperty = column.Property;
if (column.Property.Contains('.'))
{
destProperty = destProperty.Replace(".", "");
var propertyParts = column.Property.Split('.');
foreach (var member in propertyParts)
{
body = Expression.Property(body, member); // property with nested type mapping. e.g: Sensor.SubType.Name => SensorDTO.SubTypeName
if (body.Type.GetGenericTypeDefinition().IsAssignableFrom(typeof(ICollection<>))) // This is a collection, we need to project something on this nested property.
{
// something something here about projecting nested List<T> onto the DTO.
}
}
}
else
{
var mi = typeof(Sensor).GetProperty(column.Property); // one to one mapping - e.g. Sensor.Id => SensorDTO.Id
body = Expression.Property(body, mi);
}
var destinationProperty = typeof(SensorDTO).GetProperty(destProperty);
var binding = Expression.Bind(destinationProperty, body);
bindings.Add(binding);
}
var init = Expression.MemberInit(row, bindings);
return Expression.Lambda<Func<Sensor, SensorDTO>>(init, selectParam);
}
private class Column
{
public string Property { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment