Saturday, July 26, 2014

Different way of mapping with EFCodeFirst

Recently I have been working Entity Framework Code First 6.0 and it’s awesome. I am in love with it. It has got great fluent API and we can do anything with that. It’s also promotes Convention over configuration which I love so far.

I have seen people are more confused about how we can map table to class via Entity framework via code first. So this post is going to be in same series. In this post I’m going to write about different ways to mapping table to class. I have already written two post about in details.

Entity Framework code first and Inheritance–Table per hierarchy
Entity framework code first and inheritance- Table Per Type

In this blog post I will give you tips and tricks to map class(type) with database table.

As you know all mapping logic belongs to OnModelCreatingMethod and you need to override method like following and write a logic there.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

    base.OnModelCreating(modelBuilder);
}

Followings are few options for mapping class to table.

Specifying a type you don’t want to map to a table:

modelBuilder.Ignore<Employee>(); 

Mapping a Class to Table with Model Builder:

modelBuilder.Entity<Employee>().ToTable("Employee");

Mapping a Class to Table at Entity Level:

using System.ComponentModel.DataAnnotations.Schema;

namespace EntityCodeFirstInheritance
{
    [Table("Employee")]
    public class Employee 
    {
        public int  EmployeeId { get; set; }
        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Designation { get; set; }
    }
}

This is very basic concepts of mapping in Entity Code First. We are going to explore some other type of complex mapping in next post related to entity code first.

Hope you like it. Stay tuned for more!!.
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews