How to Use ‘Code First’ in Entity Framework 4 CTP 5 to Map to Existing Databases

January 13, 2011 · 2 comments

in ASP.NET MVC,Code First,Entity Framework

About 6 months back I blogged about using the Code First feature of Entity Framework 4 CTP 4 to map to existing databases that doesn’t fit the conventions of Entity Framework Code First. Since then the EF Team has released CTP5 which has a much better support for mapping POCOs to existing databases.

Let’s say we are mapping our POCOs to tables posts & comments where the column names are in lower case with ‘_’ between words, ie. post_id.

Our POCOs are defined as follows.

public class Post {
    public int ID { get; set; }

    public string Title { get; set; }

    [DataType(DataType.MultilineText)]
    public string Text { get; set; }

    public DateTime PublishDate { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

public class Comment {
    public int ID { get; set; }

    public Post Post { get; set; }

    [DataType(DataType.MultilineText)]
    public string Text { get; set; }

    public string Author { get; set; }
}

This is how we map those POCOs to the table schema above.

public class BlogContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Comment> Comments { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        /* Map the Post POCO with 'post' table. */
        var postConfig = builder.Entity<Post>();
        postConfig.Property(p => p.ID).HasColumnName("id");
        postConfig.Property(p => p.PublishDate).HasColumnName("publish_date");
        postConfig.Property(p => p.Text).HasColumnName("text");
        postConfig.Property(p => p.Title).HasColumnName("title");
        postConfig.ToTable("posts");

        /* Map the Comments POCO with 'comments' table. */
        var commentConfig = builder.Entity<Comment>();
        commentConfig.Property(c => c.ID).HasColumnName("id");            
        commentConfig.Property(c => c.Text).HasColumnName("text");
        commentConfig.Property(c => c.Author).HasColumnName("author");

        //Map the foreign key column not exposed via the Comment class.
        commentConfig.HasRequired(c => c.Post).WithMany(p => p.Comments).IsIndependent()
            .Map(m => m.MapKey(p => p.ID, "post_id"));

        commentConfig.ToTable("comments");
    }
}

Pretty sweet ! Enjoy.

Previous post:

Next post: