Skip to content

Instantly share code, notes, and snippets.

@mikecole
Created October 6, 2013 23:31
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 mikecole/6860501 to your computer and use it in GitHub Desktop.
Save mikecole/6860501 to your computer and use it in GitHub Desktop.
Data Context w/ Custom Configuration Classes
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using EntityFrameworkExtraMile.Web.Domain.Model;
namespace EntityFrameworkExtraMile.Web.DataAccess
{
public class BlogContext : DbContext
{
public BlogContext()
: base("Blog")
{
}
public DbSet<Author> Authors { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); //Remove the plurals!
modelBuilder.Configurations.Add(new PostConfiguration());
modelBuilder.Configurations.Add(new CategoryConfiguration());
modelBuilder.Configurations.Add(new AuthorConfiguration());
modelBuilder.Configurations.Add(new JobTitleConfiguration());
}
}
public class PostConfiguration : EntityTypeConfiguration<Post>
{
public PostConfiguration()
{
HasKey(post => post.ID);
Property(post => post.Title).HasMaxLength(150).IsRequired();
Property(post => post.Title).IsRequired();
HasRequired(post => post.Author)
.WithMany(author => author.Posts)
.Map(configuration => configuration.MapKey("AuthorID"));
HasRequired(post => post.Category)
.WithMany(category => category.Posts)
.Map(post => post.MapKey("PostCategoryID"));
}
}
public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
public CategoryConfiguration()
{
HasKey(cat => cat.ID);
Property(cat => cat.Name).HasMaxLength(50).IsRequired();
}
}
public class AuthorConfiguration : EntityTypeConfiguration<Author>
{
public AuthorConfiguration()
{
HasKey(author => author.ID);
Property(author => author.Name).HasMaxLength(50).IsRequired();
Property(author => author.TwitterHandle).HasMaxLength(50);
HasOptional(author => author.JobTitle)
.WithMany(title => title.Authors)
.Map(author => author.MapKey("JobTitleID"));
}
}
public class JobTitleConfiguration : EntityTypeConfiguration<JobTitle>
{
public JobTitleConfiguration()
{
HasKey(title => title.ID);
Property(title => title.Title).HasMaxLength(50).IsRequired();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment