Skip to content

Instantly share code, notes, and snippets.

@lbargaoanu
Created March 2, 2016 09:42
Show Gist options
  • Save lbargaoanu/b5f75a6ff289cbf4f98d to your computer and use it in GitHub Desktop.
Save lbargaoanu/b5f75a6ff289cbf4f98d to your computer and use it in GitHub Desktop.
EF Self Referencing Model
using System;
using System.Linq;
using System.Data.Entity;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using System.Collections.Generic;
namespace SelfReferencingWithViewModel
{
class Program
{
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<BlogComment, BlogCommentViewModel>();
});
var mapper = config.CreateMapper();
config.AssertConfigurationIsValid();
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Configuration>());
using(var ctx = new MyContext())
{
var list =
ctx.BlogComments
//.Select(a => new { a.Children, a.Body, a.Id, a.Reply, a.ReplyId })
.ToList() // fills the childs list too
.Where(x => x.Reply == null) // for TreeViewHelper
.ToList();
foreach(var item in list)
{
foreach(var child in item.Children)
{
Console.WriteLine(child.Id);
}
Console.WriteLine(item.Id);
}
var result = mapper.Map<List<BlogCommentViewModel>>(list);
foreach(var item in result)
{
foreach(var child in item.Children)
{
Console.WriteLine(child.Id);
}
Console.WriteLine(item.Id);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment