I would like to map an entity with a complex type to another entity. However, on the last line in the Main method a
System.NotSupportedException: Cannot compare elements of type 'ConsoleApplication2.ComplexType'. Only primitive types, enumeration types and entity types are supported.
exception is raised.
How to fix it?
I am aware I can flatten the complex type properties to the entity. However, it involves lots of code duplication so I strongly prefer a solution which does not need me to flatten the complex type properties to the entity. The complex type my itself contain other complex type, so the solution should allow nesting complex types to complex types.
Entity Framework 6.1.3, AutoMapper 3.3.1 and 4.0.4, SQL Server 2014 SP1 Express, VS 2015, .NET 4.5.2 and 4.6.
It works if .SingleOrDefault(x => x.Id == 1) or .ProjectTo<MappedEntity>() is removed.
If still does not work if the .SingleOrDefault(x => x.Id == 1) is rewritten as .Where(x => x.Id == 1).ToList().SingleOrDefault();.
GitHub Issue: https://github.com/AutoMapper/AutoMapper/issues/925
using System.Data.Entity;
using System.Linq;
using AutoMapper;
using AutoMapper.QueryableExtensions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseAlways<ClientContext>());
Mapper.CreateMap<Entity, MappedEntity>();
Mapper.CreateMap<ComplexType, MappedComplexType>();
var clientContext = new ClientContext();
clientContext.Set<Entity>().ProjectTo<MappedEntity>().SingleOrDefault(x => x.Id == 1);
}
}
class ClientContext : DbContext
{
public virtual DbSet<Entity> Entities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Entity>().HasKey(x => x.Id);
modelBuilder.ComplexType<ComplexType>();
}
}
class Entity
{
public virtual int Id { get; set; }
public virtual ComplexType ComplexType { get; set; }
}
class ComplexType
{
public virtual string Field { get; set; }
}
class MappedEntity
{
public virtual int Id { get; set; }
public virtual MappedComplexType ComplexType { get; set; }
}
class MappedComplexType
{
public virtual string Field { get; set; }
}
}