Thursday, July 2, 2015

Entity Framework with MVC5 Part1

We all have been using EF with ASP.Net so i wanted to try how does it work in MVC5 . so here is what is did:

Create a Class Model :Projects"



   public class Projects
    {
        [Key]
        public int projectid { get; set; }
        public string projectName { get; set; }
        public ICollection<WBS> WBs { get; set; }
    }
we see that Each Project has WBS element . so i created WBS Class Also 

public class WBS
    {
        [Key]
        public int WBSid { get; set; }
        public string WBSName { get; set; }
    }

 Note that Key has to be mentioned . otherwise EF will give Build error

Then I Created Context Class 

  public class ProjectWBSContext:DbContext
    {
        public DbSet<Projects> Projects { get; set; }
        public DbSet<WBS> WBSs { get; set; }
    }
so Final thing is creating a controller
we can create an empty controller or we can create scaffolding EF controller with edit/view 

i chose to start with scaffolding so that my job is quicker and easier . VS will create all the rest of the actions automatically . also the views

NOTE: Chose proper model and Context class while scaffolding 

Now Run the Solution 
You get the nice interface .. 


 
 Well This is actually code first Approach where you define the class first and DB tables will be automatically created . 
CRUD Operation are easier with Scaffolding .


No comments:

Post a Comment