Skip to content

Instantly share code, notes, and snippets.

@evanlarsen
Created January 6, 2014 22:37
Show Gist options
  • Save evanlarsen/8291083 to your computer and use it in GitHub Desktop.
Save evanlarsen/8291083 to your computer and use it in GitHub Desktop.
Experimenting with Fluent Interface and Generics
using CQRS01.Domain.Entities;
using CQRS01.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace CQRS01.Web.Framework.Mapping
{
public class Test
{
public Test()
{
ModelStateMappings.Map<Book, BookViewModel>()
.Property(p => p.Author, p => p.Author)
.Property(p => p.Name, p => p.Name)
.Property(p => p.Price, p => p.Price);
}
}
internal static class ModelStateMappings
{
private static IList<ModelMappings> mappings;
public static ModelStateMappings()
{
mappings = new List<ModelMappings>();
}
public static ModelMappings<TDomainModel, TViewModel> Map<TDomainModel, TViewModel>()
{
var mm = new ModelMappings<TDomainModel, TViewModel>();
mappings.Add(mm);
return mm;
}
}
internal class ModelMappings
{
public Type DomainModelType { get; set; }
public Type ViewModelType { get; set; }
public IList<PropertyMapping> PropertyMappings { get; set; }
public ModelMappings()
{
PropertyMappings = new List<PropertyMapping>();
}
}
internal class ModelMappings<TDomainModel, TViewModel> : ModelMappings
{
public ModelMappings() : base()
{
DomainModelType = typeof(TDomainModel);
ViewModelType = typeof(TViewModel);
}
public ModelMappings<TDomainModel, TViewModel> Property(Expression<Func<TDomainModel, object>> domainProperty, Expression<Func<TViewModel, object>> viewModelProperty)
{
// must cast expressions to the signature of Expression<Func<object, string>> in order add to the list
Expression castDomainProp = Expression.Convert(domainProperty.Body, typeof(object));
var convertedDomainProp = Expression.Lambda<Func<object, object>>(castDomainProp, domainProperty.Parameters);
Expression castViewModelProp = Expression.Convert(domainProperty.Body, typeof(object));
var convertedViewModelProp = Expression.Lambda<Func<object, object>>(castViewModelProp, viewModelProperty.Parameters);
PropertyMappings.Add(new PropertyMapping { DomainProperty = convertedDomainProp, ViewModelProperty = convertedViewModelProp });
return this;
}
}
internal class PropertyMapping
{
public Expression<Func<object, object>> DomainProperty { get; set; }
public Expression<Func<object, object>> ViewModelProperty { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment