我有一个执行创建,编辑,删除和读取操作的存储过程。
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
我在Controller上调用了这个程序。
// 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行:返回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
然后创作就没事了。但现在删除功能将无效。
答案 0 :(得分:4)
当你在Delete
这样的方法中调用它时,你也需要传递其他参数。我想参数化@regid就像你最后发布的那样结束了。
db.Database.ExecuteSqlCommand("dbo.CURDOpSP @p0, @p1,@p2,@p3@,@p4,@p5", "Delete","","","","",register.RegisterId);