Skip to content

Instantly share code, notes, and snippets.

Created February 18, 2013 09:16
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 anonymous/0e61d1088ac0e6728282 to your computer and use it in GitHub Desktop.
Save anonymous/0e61d1088ac0e6728282 to your computer and use it in GitHub Desktop.
AutoMapper and EF demo
class Program
{
static void Main(string[] args)
{
Database.SetInitializer(new Initializer());
Mapper.CreateMap<TestObjectView, TestObject>();
Mapper.CreateMap<List<TestChildObjectView>, List<TestChildObject>>();
Mapper.CreateMap<TestChildObjectView, TestChildObject>();
var builder = new ContainerBuilder();
builder.RegisterType<Initializer>();
var viewModel = new TestObjectView()
{
Id = 666,
Child = new TestChildObjectView() {Id = 666},
TestString = "Evil",
Children = new List<TestChildObjectView>(){new TestChildObjectView(){Id = 555}, new TestChildObjectView(){Id = 777}}
};
using(var e = new EFRepros())
{
var testObject = e.TestObjects.First();
Mapper.Map(viewModel, testObject);
}
}
}
public class Initializer : DropCreateDatabaseAlways<EFRepros>
{
protected override void Seed(EFRepros context)
{
base.Seed(context);
var child1 = new TestChildObject() { Id = 1};
var child2 = new TestChildObject() {Id = 2};
var child3 = new TestChildObject() { Id=3};
context.TestChildObjects.Add(child1);
context.TestChildObjects.Add(child2);
context.TestChildObjects.Add(child3);
var test = new TestObject()
{
Id = 1,
Children = new List<TestChildObject>() {child1, child2},
Child = child3,
TestString = "hello"
};
context.TestObjects.Add(test);
context.SaveChanges();
}
}
public class EFRepros : DbContext
{
public DbSet<TestObject> TestObjects { get; set; }
public DbSet<TestChildObject> TestChildObjects { get; set; }
public DbSet<GrandChildObject> GrandChildObjects { get; set; }
}
public class TestObjectView
{
public int Id { get; set; }
public string TestString { get; set; }
public TestChildObjectView Child { get; set; }
public List<TestChildObjectView> Children { get; set; }
}
public class TestChildObjectView
{
public int Id { get; set; }
}
public class TestObject
{
public int Id { get; set; }
public string TestString { get; set; }
public virtual TestChildObject Child { get; set; }
public virtual List<TestChildObject> Children { get; set; }
}
public class TestChildObject
{
public int Id { get; set; }
public virtual GrandChildObject GrandChildObject { get; set; }
}
public class GrandChildObject
{
public int Id { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment