none
MVC adding edit and delete to database from home controller

    Question

  • Hey guys...

    So iv just completed the youtube tutorial http://www.youtube.com/watch?v=LAhZ29p9f4k

    which shows us how to create a DB, add it to a data model, then use the default methods (create,edit,delete) in homecontroller to use the DB

    My code cosists of...so far this allows me to use the Index to create but im running into difficulties when I tried the edit, and delete functions myself

    namespace MvcApplication7.Controllers
    {
        public class HomeController : Controller
        {
            private MoviesDBEntities _entities = new MoviesDBEntities();
            //
            // GET: /Home/
    
            public ActionResult Index()
            {
                return View(_entities.MovieTable1.ToList());
            }
    
            //
            // GET: /Home/Details/5
    
            public ActionResult Details(int id)
            {
                return View();
            }
    
            //
            // GET: /Home/Create
    
            public ActionResult Create()
            {
                return View();
            }
    
            //
            // POST: /Home/Create
    
            [HttpPost]
            //public ActionResult Create(FormCollection collection)
            public ActionResult Create([Bind(Exclude = "id")]MovieTable1 movieToCreate)
            {
                try
                {
                    // TODO: Add insert logic here
                    _entities.AddToMovieTable1(movieToCreate);
                    _entities.SaveChanges();
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }


    So...for edit I have used:

    // GET: /Home/Edit/5
     
            public ActionResult Edit(int id)
            {
                return View();
            }
    
            //
            // POST: /Home/Edit/5
    
            [HttpPost]
            //public ActionResult Edit(int id, FormCollection collection)
            public ActionResult Edit([Bind(Exclude = "id")]MovieTable1 movieToCreate)
            {
                try
                {
                    // TODO: Add update logic here
                    
                   //so i need to insert a line of code here to say something like update
                    //I was using the previous code:
                   //_entities.AddToMovieTable1(movieToCreate);
                    _entities.SaveChanges();           
     
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }

    so where i use '_entities.addToMovieTable1(movieToCreate);' in the edit function I have looked for an edit or update selection from the drop down but they don't appear?  

    _entities.???(movieToCreate)???

    Could someone advise me what I am missing

    ------------------------------------------------------------

    below you will find my code for delete...however when i run this it throws me a nullExeptionRef from the .asp page

    public ActionResult Delete(int id)
            {
                return View();
            }
    
            //
            // POST: /Home/Delete/5
    
            [HttpPost]
            //public ActionResult Delete(int id, FormCollection collection)
            public ActionResult Delete([Bind(Exclude = "id")]MovieTable1 movieToDelete)
            {
                try
                {
                    // TODO: Add delete logic here
                    _entities.DeleteObject(movieToDelete);
                    _entities.SaveChanges();
     
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }

    and in my delete.aspx page:


           
    <div class="display-label">Id</div>
           
    <div class="display-field"><%: Model.Id %></div>
           
           
    <div class="display-label">Title</div>
           
    <div class="display-field"><%: Model.Title %></div>

    any help would be greatful

    Thanks


    Friday, October 19, 2012 7:07 PM

All replies

  • So that's an older video, some things have changed with regards to Entity Framework. 

    So, the object you're using. The methods that are available (if you're using the most up-to-date versions of everything) would be:

    _entities.MovieTable1.Add();
    _entities.MoveTable1.Remove();
    _entities.MovieTable1.SaveChanges; 

    For adding, you create an entity:

    var entity = new MovieTable1() {
    Name = "Name",
    Director = "Director",
    DateReleased = DateTime.Now
    };

    *Notice that you don't provide an Id there. When you save a new entity, the database does the work of creating an Id for you. Which is why in your Create method you have Create(Bind[except=Id)). 

    Now to add your new movie entity, you do:

    _entites.MovieTable1.Add(_entity);
    _entities.MovieTable1.SaveChanges();

    To address the Edit and Delete methods. 

    So when you are showing all the records to a viewer on the webpage, if you look at the Views, there is a spot for the ID field. So when you select the record you want to edit (or delete), that Id is passed back so that you know which record needs to be edited. Otherwise there would be no way of knowing. Soooo, on the Edit and Delete, they should look like this:

    [HttpPost]
    public ActionResult Edit(MovieTable1 entityToEdit);

    and 

    [HttpPost]
    public ActionResult Delete(MovieTable1 entityToDelete);

    Notice on both of those, the [Bind(except="id")] is not there. That's because we want the Id to be a part of the entity. 

    So now let's say you're in the Edit method. Here's where it gets a little confusing. So, you need to get that record from the database to work with it:

    var getEntityFromDatabase = _entities.MovieTable1.Where(d => d.Id == entityToEdit.Id);

    Now that you have the record, you can edit or remove it (it's getting edited in the code below):

    getEntityFromDatabase .Name = "Brand New Name"; or
    getEntityFromDatabase .Director = "Clint Eastwood"

    So your entity now has new values in it. You then call, 

    _entities.SaveChanges();

    That's it. Just SaveChanges. There is no Edit or method explicitly. Just accept that it magically gets saved back into the databaes. 

    Now delete has a method but it's called Remove. 

    Again, you get a new entity using the Id of the entity in the Delete(MovieTable1 deleteThisEntity);

    getEntityFromDatabase = _entities.MovieTable1.Where(d => d.Id == deleteThisEntity.Id);

    Then you call:

    _entities.MovieTable1.Remove(getEntityFromDatabase);
    _entities.SaveChanges();

    Finally, to address the question you had about about the NullReferenceExcpetioin. Every time you're going to do an operation on an entity, you need to make sure it's not null. So for instance in your Delete method, the movieToDelete object is coming into the call as null. 

    So when you call, _entities.DeleteObject(movieToDelete ) (which again, you shouldn't use. use the way I outlined above), an exception will get thrown. You have to check for null first like:

    if(movieToDelete != null)
    {
        var _getEntityFromDatabase = _entities.MovieTable1.Where(d => d.Id == movieToDelete .Id);
    // And check one more time to make sure it's not null
        if(_getEntityFromDatabaes != null)
        {
            _entities.MovieTable1.Remove(_getEntityFromDatabaes);
    _entities.SaveChanges();
        }
    }






    Saturday, October 20, 2012 7:32 AM
  • Hi xnaLearner,

    From your description , I ‘d like to move this post to  the most related forum .

    There has more  experts in this aspect  , so you will get  better support and  may have more luck getting answers .

    Thanks for your understanding .

    Regards ,


    Lisa Zhu [MSFT]
    MSDN Community Support | Feedback to us

    Tuesday, October 23, 2012 1:11 AM