Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gius
Last active October 5, 2018 14:10
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 gius/d1cff1dea8686c6d822a1ef290a042bc to your computer and use it in GitHub Desktop.
Save gius/d1cff1dea8686c6d822a1ef290a042bc to your computer and use it in GitHub Desktop.
EF Core + Automapper
// required NuGet packages: AutoMapper (7.0.1), Microsoft.EntityFrameworkCore.SqlServer (2.1.0 and later)
using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
namespace EfCoreAutomapper
{
public class Program
{
public static void Main(string[] args)
{
Mapper.Initialize(config =>
{
config.CreateMap<Customer, CustomerDto>();
config.CreateMap<Customer, SimpleCustomerDto>();
});
using (var context = new Context())
{
context.Database.Migrate();
// calls SELECT [x].[ID], [x].[Name] FROM[Customers] AS[x] ORDER BY [x].[Name], [x].[ID]
var queryNoMapper = context.Customers
.OrderBy(x => x.ID)
.OrderBy(x => x.Name)
.ToList();
// calls SELECT [x].[ID], [x].[Name] FROM[Customers] AS[x] ORDER BY [x].[Name], [x].[ID]
var queryWithMapper = context.Customers
.OrderBy(x => x.ID)
.OrderBy(x => x.Name)
.ProjectTo<SimpleCustomerDto>()
.ToList();
// calls SELECT [x].[ID], [x].[Name] FROM[Customers] AS[x] ORDER BY [x].[ID], [x].[Name]
var queryWithMapperWrong = context.Customers
.OrderBy(x => x.ID)
.OrderBy(x => x.Name)
.ProjectTo<CustomerDto>()
.ToList();
// it does not matter whether OrderBy statements are before or after the ProjectTo call
}
}
}
public class Context : DbContext
{
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=AutomapperBug;Trusted_Connection=True;");
}
}
#region Entities
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
public List<CustomerAddress> Addresses { get; set; }
}
public class CustomerAddress
{
public int ID { get; set; }
public int CustomerID { get; set; }
public string Street { get; set; }
public string City { get; set; }
}
#endregion Entities
#region DTOs
public class CustomerDto
{
public int ID { get; set; }
public string Name { get; set; }
public List<CustomerAddressDto> Addresses { get; set; }
}
public class SimpleCustomerDto
{
public int ID { get; set; }
public string Name { get; set; }
// Note: the only difference from CustomerDto is that the Addresses property is missing here
}
public class CustomerAddressDto
{
public string Street { get; set; }
public string City { get; set; }
}
#endregion DTOs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment