我有一个存储过程,可以执行创建、编辑、删除和读取操作。
ALTER PROCEDURE [dbo].[CURDOpSP]
@operation varchar(50),
@regid int = 0,
@fname varchar(50) = null,
@lname varchar(50) = null,
@phone varchar(50) = null,
@email varchar(50) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
if(@operation = 'Insert')
BEGIN
insert into Register(fname,lname,phone,email,status)values(@fname,@lname,@phone,@email,0);
END
else if(@operation = 'Select')
BEGIN
select * from Register where status = 0;
END
else if(@operation = 'Edit')
BEGIN
update Register set fname= @fname, lname = @lname, phone = @phone, email = @email where RegisterId = @regid;
END
else if(@operation = 'Delete')
BEGIN
Update Register set status = 1 where RegisterId = @regid;
END
END
我已经在控制器上调用了这个过程。
// GET: /Employee/Create
public ActionResult Create()
{
return View();
}
// POST: /Employee/Create
[HttpPost]
public ActionResult Create(Register register)
{
if (ModelState.IsValid)
{
db.Database.ExecuteSqlCommand("dbo.CURDOpSP @p0, @p1, @p2, @p3, @p4", "Insert", register.fname, register.lname, register.phone, register.email);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(register);
}
// POST: /Employee/Delete/5
public ActionResult Delete(int id)
{
Register register = db.Registers.Find(id);
if (register == null)
{
return HttpNotFound();
}
db.Database.ExecuteSqlCommand("dbo.CURDOpSP @p0, @p1", "Delete",register.RegisterId);
db.SaveChanges();
return RedirectToAction("Index");
}
当我尝试创建新记录时,出现以下错误:
其他三个操作正常运行。将 nvarchar 数据类型转换为 int 时出错。
来源错误:
第 40 行:if (ModelState.IsValid)
第 41 行:{
第 42 行:db.Database.ExecuteSqlCommand("dbo.CURDOpSP @p0, @p1, @p2, @p3, @p4", "Insert", register.fname, register.lname, register.phone, register.email);
第 43 行:db.SaveChanges();
第 44 行:return RedirectToAction("Index");
如果我在存储过程的参数声明末尾插入参数 @regid,如下所示:
ALTER PROCEDURE [dbo].[CURDOpSP]
@operation varchar(50),
@fname varchar(50) = null,
@lname varchar(50) = null,
@phone varchar(50) = null,
@email varchar(50) = null,
@regid int = 0
然后创建操作将正常。但是现在删除功能无法正常工作。