Created
December 11, 2015 10:10
-
-
Save lbargaoanu/a8aa12e1ddc100c7aad0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void Main(string[] args) | |
{ | |
Mapper.Initialize(config => | |
{ | |
config.CreateMap<Category, CategoryDto>(); | |
config.CreateMap<Article, ArticleDto>(); | |
}); | |
Mapper.AssertConfigurationIsValid(); | |
var context = new AppDbContext(); | |
var articles = context.Articles.ProjectTo<ArticleDto>().ToList(); | |
articles.Dump(); | |
} | |
class Initializer : DropCreateDatabaseAlways<AppDbContext> | |
{ | |
protected override void Seed(AppDbContext context) | |
{ | |
var category = new Category { Name = "first" }; | |
context.Categories.Add(category); | |
context.SaveChanges(); | |
context.Articles.AddRange(new[]{ | |
new Article { Content = "one", Title = "q1", Category = category }, | |
new Article { Content = "two", Title = "q2", Category = new Category { Name = "second" }}, | |
new Article { Content = "three", Title = "q3", Category = category }, | |
}); | |
} | |
} | |
public class AppDbContext : DbContext | |
{ | |
public AppDbContext() | |
{ | |
Database.SetInitializer(new Initializer()); | |
} | |
protected override void OnModelCreating(DbModelBuilder builder) | |
{ | |
base.OnModelCreating(builder); | |
builder.Entity<Article>() | |
.HasRequired(a => a.Category) | |
.WithMany(c => c.Articles) | |
.HasForeignKey(n => n.CategoryId) | |
.WillCascadeOnDelete(); | |
} | |
public DbSet<Article> Articles { get; set; } | |
public DbSet<Category> Categories { get; set; } | |
} | |
public class Article | |
{ | |
public int Id { get; set; } | |
[Required, MaxLength(256)] | |
public string Title { get; set; } | |
[Required] | |
public string Content { get; set; } | |
public DateTimeOffset Created { get; set; } | |
public Category Category { get; set; } | |
public int CategoryId { get; set; } | |
} | |
public class ArticleDto | |
{ | |
public int Id { get; set; } | |
public string Title { get; set; } | |
public string Content { get; set; } | |
public DateTimeOffset Created { get; set; } | |
public CategoryDto Category { get; set; } | |
} | |
public class Category | |
{ | |
public Category() | |
{ | |
Articles = new List<Article>(); | |
} | |
public int Id { get; set; } | |
[Required, MaxLength(256)] | |
public string Name { get; set; } | |
public List<Article> Articles { get; set; } | |
} | |
public class CategoryDto | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment