Skip to content

Instantly share code, notes, and snippets.

@lbargaoanu
Last active October 23, 2015 14:00
Show Gist options
  • Save lbargaoanu/102001328d0b4546fe9c to your computer and use it in GitHub Desktop.
Save lbargaoanu/102001328d0b4546fe9c to your computer and use it in GitHub Desktop.
AutoMapper 4.1.0 Exception with Proxy on Inherited object with Entity Framework #945
static void Main(string[] args)
{
Database.SetInitializer(new Initializer());
Mapper.Initialize(cfg => {
cfg.CreateMap<TrainingCourse, TrainingCourseDto>().Include<TrainingCourse, ParentTrainingCourseDto>();
cfg.CreateMap<TrainingCourse, ParentTrainingCourseDto>();
cfg.CreateMap<TrainingContent, TrainingContentDto>();
});
Mapper.AssertConfigurationIsValid();
var context = new ClientContext();
var course = context.TrainingCourses.FirstOrDefault(n => n.CourseName == "Course 1");
var dto = Mapper.Map<TrainingCourseDto>(course);
dto.Dump();
}
class Initializer : DropCreateDatabaseAlways<ClientContext>
{
protected override void Seed(ClientContext context)
{
var course = new TrainingCourse{ CourseName = "Course 1" };
context.TrainingCourses.Add(course);
var content = new TrainingContent{ ContentName = "Content 1", Course = course };
context.TrainingContents.Add(content);
course.Content.Add(content);
}
}
class ClientContext : DbContext
{
public ClientContext() : base(@"Server=(localdb)\v12.0;Integrated Security=true;Initial Catalog = ClientContext;")
{
}
public DbSet<TrainingCourse> TrainingCourses { get; set; }
public DbSet<TrainingContent> TrainingContents { get; set; }
}
public class TrainingCourse
{
public TrainingCourse()
{
Content = new List<TrainingContent>();
}
public TrainingCourse(TrainingCourse entity)
{
Mapper.Map(entity, this);
}
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<TrainingContent> Content { get; set; }
}
public class TrainingContent
{
public TrainingContent()
{
}
[Key]
public int ContentId { get; set; }
public string ContentName { get; set; }
public virtual TrainingCourse Course { get; set; }
// public int CourseId { get; set; }
}
public class TrainingCourseDto
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public ICollection<TrainingContentDto> Content { get; set; }
}
public class ParentTrainingCourseDto : TrainingCourseDto
{
[IgnoreMap]
public new ICollection<TrainingContentDto> Content { get; set; }
}
public class TrainingContentDto
{
public int ContentId { get; set; }
public string ContentName { get; set; }
public ParentTrainingCourseDto Course { get; set; }
// public int CourseId { get; set; }
}
@TylerCarlson1
Copy link

LinqPad's output to result function. If you use C# statements don't have to do this, but if you write code you have to call it to get an output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment