How to add record into the database using MVC

asp.net-mvc c# entity-framework

Question

I am trying to add a record into a database but its showing me a error: An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code i get this error when i run my program, it does not even open my view in web-browser

This is my model:

public class MovieModel
{
    public int ID { set; get; }
    public string FirstName { set; get; }
    public string SecondName { set; get; }
    public DateTime DOB { set; get; }
    public string Type{ set; get; }
}

This is my controller:

namespace Movie.Controllers
{
    public class MoviesController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        //
        // GET: /Movies/
        public ActionResult AddUsers(MovieModel model)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(model);
                db.SaveChanges();
            }
            return View(model);
        }
    }
}

Second Question when up-grading my database upgrade-database how do i specify a forgone key? is this have to be done via microsoft sql server management?

1
1
3/7/2014 7:10:43 PM

Accepted Answer

This occurs when you are trying to add/insert a record in an object other than a table. Is Movie a table or a view?

If it is a table, be sure your table has a primary key which doesn't allow duplication.

If not add the primary key and update the Entity Framework model and run again.

UPDATES : You can create an empty get action. To do so, update your controller as follows

    //
    // GET: /Movies/
    public ActionResult AddStudent()
    {
        return View();
    }


     //
    // POST: /Movies/
    [Post]
    public ActionResult AddStudent(MovieModel model)
    {
        if (ModelState.IsValid)
        {
            db.Movies.Add(model);
            db.SaveChanges();
        }
        return View(model);
    }
3
12/5/2016 11:20:22 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow