gpt4 book ai didi

c# - 将数据类型 nvarchar 转换为 int 时出错 - 执行存储过程时

转载 作者:行者123 更新时间:2023-11-30 15:23:43 24 4
gpt4 key购买 nike

我有一个执行创建、编辑、删除和读取操作的存储过程。

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");
}

当我尝试创建新记录时,出现此错误:

Error converting data type nvarchar to int.

Source Error:

Line 40: if (ModelState.IsValid)

Line 41: {

Line 42: db.Database.ExecuteSqlCommand("dbo.CURDOpSP @p0, @p1, @p2, @p3, @p4", "Insert", register.fname, register.lname, register.phone, register.email);

Line 43: db.SaveChanges();

Line 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

然后创建就可以了。但是现在删除功能将不起作用。

最佳答案

在这样的Delete方法中调用时,还需要传递其他参数。我想参数 @regid 就像你最后发布的那样结束了。

db.Database.ExecuteSqlCommand("dbo.CURDOpSP @p0, @p1,@p2,@p3@,@p4,@p5", "Delete","","","","",register.RegisterId); 

关于c# - 将数据类型 nvarchar 转换为 int 时出错 - 执行存储过程时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34172709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com