Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created December 28, 2018 05:57
Show Gist options
  • Save danielplawgo/b6e38de79e47ea2be62e8102f7397058 to your computer and use it in GitHub Desktop.
Save danielplawgo/b6e38de79e47ea2be62e8102f7397058 to your computer and use it in GitHub Desktop.
Entity Framework, Automapper oraz projekcja
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
static void Main(string[] args)
{
HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
MapTest();
}
static void MapTest()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Product, ProductViewModel>()
.ForMember(dest => dest.Category, opt => opt.MapFrom(src => src.Category.Name));
});
var mapper = config.CreateMapper();
using (var db = new DataContext())
{
var products = mapper.Map<List<ProductViewModel>>(db.Products.ToList());
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public ProductType Type { get; set; }
}
public enum ProductType
{
Virtual,
Physical
}
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public string Type { get; set; }
}
static void Main(string[] args)
{
HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
ProjectToTest();
}
static void ProjectToTest()
{
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<Product, ProductViewModel>()
.ForMember(dest => dest.Category, opt => opt.MapFrom(src => src.Category.Name));
});
var mapper = config.CreateMapper();
using (var db = new DataContext())
{
var products = mapper.ProjectTo<ProductViewModel>(db.Products).ToList();
}
}
var products = db.Products.Select(p => new ProductViewModel()
{
Id = p.Id,
Name = p.Name,
Category = p.Category.Name
}).ToList();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment