如何使用MVC将记录添加到数据库中 [英] How to add record into the database using MVC
问题描述
我正在尝试在数据库中添加记录,但显示错误: EntityFramework.dll中发生了类型为System.Data.Entity.Infrastructure.DbUpdateException的异常,但未处理在用户代码
我得到这个错误,当我运行我的程序,它甚至没有打开我的视图在网络浏览器
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
这是我的模型:
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; }
}
这是我的控制器:
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);
}
}
}
第二个问题当我的数据库升级时 upgrade-database
我如何指定一个被放弃的密钥?这是否必须通过微软sql server管理完成?
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?
推荐答案
当您尝试添加/插入记录时,会发生这种情况除表
之外的对象。是电影
表或视图?
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);
}
这篇关于如何使用MVC将记录添加到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!