Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to go through all relevant question answer of my topic but that is not helping me.

I am facing problem in creating Controller with views, using EF in visual studio.

I am following approach to speed up development of client projects.
I use to create database with tables and also create their relationships
Using database first approach, create the entities of all tables, 4.Create ViewModel for each class with data annotations for validation.
Now when I use to create a controller using Controller with views, using EF, its create controller and view using this ViewModel class.
Problem is that this ViewModel does not exist in DB, as I created this just to get data from user.so if I try to save this it gives me an error that this view model does not exist. 6.Now if I use entities that EF has created for me to create controller so that will not be a good approach.

I have to go through different solution after googling, but my point is what is the benefit of that DB first approach if I have to go all different solution. I think in MVC 2.0 or 3.0 there is an option that users can select view model class and then bind it to the desired model class that actually saves data into the respective table. Now there is just one option select DB context What is the best approach to use Controller with views, using EF at maximum to speed up development



My concern is as this is done using Myviewmodel, how can CRUD operation be performed as actually MyModel class is that can be used to communicate with database using EF not the MYviewmodel class.


Is it not simple that we create all views of CRUD using viewmodel class and on controller level perform CRUD operation using model entity that was generated by EF using code firs approach.

What I have tried:

here is mymodelclass


C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QuotesAdmin.DAL
{
    public class MyModel
    {
        public long lIPID { get; set; }

        public string sIPTitle { get; set; }

        public string sFATitle { get; set; }

        public int nProgrammeID { get; set; }

        public System.DateTime dtModifiedDate { get; set; }
        public bool bDeleted { get; set; } = false;
        public string sRemarks { get; set; } = "";
    }
}


here is MyViewModel class


C#
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace QuotesAdmin.DAL
{
    public class MyViewModel
    {
        [Key]

        public long lIPID { get; set; }
        [Display(Name = "IP Title")]
        [Required]
        public string sIPTitle { get; set; }
        [Display(Name = "FA Title")]
        [Required]
        public string sFATitle { get; set; }
        [Display(Name = "Programme Title")]
        [Required]
        public int nProgrammeID { get; set; }
        [Display(Name = "Created Date")]
        [Required]
        public System.DateTime dtModifiedDate { get; set; }
        public bool bDeleted { get; set; } = false;
        public string sRemarks { get; set; } = "";
    }
}

when I create controller using Controller with views, using EF in visual studio,

it will create controller and different view as follow.


C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using QuotesAdmin.DAL;
using QuotesAdmin.Models;

namespace QuotesAdmin.Controllers
{
    public class MyViewModelsController : Controller
    {
        private PPAFEntities db = new PPAFEntities();

        // GET: MyViewModels
        public ActionResult Index()
        {
            return View(db.MyViewModels.ToList());
        }

        // GET: MyViewModels/Details/5
        public ActionResult Details(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MyViewModel myViewModel = db.MyViewModels.Find(id);
            if (myViewModel == null)
            {
                return HttpNotFound();
            }
            return View(myViewModel);
        }

        // GET: MyViewModels/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: MyViewModels/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "lIPID,sIPTitle,sFATitle,nProgrammeID,dtModifiedDate,bDeleted,sRemarks")] MyViewModel myViewModel)
        {
            if (ModelState.IsValid)
            {
                db.MyViewModels.Add(myViewModel);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(myViewModel);
        }

        // GET: MyViewModels/Edit/5
        public ActionResult Edit(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MyViewModel myViewModel = db.MyViewModels.Find(id);
            if (myViewModel == null)
            {
                return HttpNotFound();
            }
            return View(myViewModel);
        }

        // POST: MyViewModels/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "lIPID,sIPTitle,sFATitle,nProgrammeID,dtModifiedDate,bDeleted,sRemarks")] MyViewModel myViewModel)
        {
            if (ModelState.IsValid)
            {
                db.Entry(myViewModel).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(myViewModel);
        }

        // GET: MyViewModels/Delete/5
        public ActionResult Delete(long? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            MyViewModel myViewModel = db.MyViewModels.Find(id);
            if (myViewModel == null)
            {
                return HttpNotFound();
            }
            return View(myViewModel);
        }

        // POST: MyViewModels/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(long id)
        {
            MyViewModel myViewModel = db.MyViewModels.Find(id);
            db.MyViewModels.Remove(myViewModel);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


here is create view


@model QuotesAdmin.Models.MyViewModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()

        <div class="form-horizontal">
            <h4>MyViewModel</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model.sIPTitle, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.sIPTitle, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.sIPTitle, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.sFATitle, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.sFATitle, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.sFATitle, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.nProgrammeID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.nProgrammeID, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.nProgrammeID, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.dtModifiedDate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.dtModifiedDate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.dtModifiedDate, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.bDeleted, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.bDeleted)
                        @Html.ValidationMessageFor(model => model.bDeleted, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.sRemarks, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.sRemarks, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.sRemarks, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900