Thursday, July 2, 2015

Entity Framework With Empty Controller - ADD

Earlier we have done the CRUD operation using scaffolding . Now lets do it explicitly without auto generated codes .

So for that once you create a class "Projects" add New item (SQL server Database) in App_data folder and name it EFCode1.mdf

Just in case you wish to add a new model class , do it this way


      public class Projects
    {
        [Key]
        public int projectid { get; set; }
        public string projectName { get; set; }
        public ICollection<WBS> WBs { get; set; }
    }
ensure you have created Context class
 
   public class ProjectWBSContext:DbContext
    {
        public DbSet<Projects> Projects { get; set; }
        public DbSet<WBS> WBSs { get; set; }
    }


Create an empty controller . specify appropriate model class and context

now add an action method inside it


  public ActionResult Index()
        {
            ProjectWBSContext pwbs = new ProjectWBSContext();
         
            var Projects = pwbs.Projects.ToList();
            return View(Projects);
        }
Add a view with option "List"

run the solution you will be able to see it has generated the database and the table but table is empty and you can see that in front end also. grid is empty . 

Note : in web config file ensure that Name of the connection string is same as your context class .change .mdf file name also

    <add name="ProjectWBSContext" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\EFCode1.mdf;Integrated Security=True"/>

Now create another action method for Create . 


[HttpGet]
        public ActionResult Create()
        {
            ProjectWBSContext pwbs = new ProjectWBSContext();

            return View(new Projects());
        }

        [HttpPost]
        public ActionResult Create(Projects Proj)
        {
            if(ModelState.IsValid)
            {
                ProjectWBSContext pwbs = new ProjectWBSContext();
                pwbs.Projects.Add(Proj);
                pwbs.SaveChanges();
                return Redirect("Index");
            }

            else { return View(Proj); }

          
        }
create a view with option "Create"
Run the solution 
now you will be able to add the items to the table . 

No comments:

Post a Comment