gpt4 book ai didi

asp.net-mvc-3 - 如何将异常从存储过程传递到我的 Post Action 方法

转载 作者:行者123 更新时间:2023-12-04 18:20:46 25 4
gpt4 key购买 nike

我有以下将两个参数传递给存储库方法的 Post Action 方法:-

 [HttpPost]
public void Delete(string id, int classid )
{
repository.Deleteuserclass(id, classid); }

存储库方法在哪里:-

public void Deleteuserclass(string a, int u)

{
entities.deleteuserclass(a,u);}

最后,存储库方法将调用以下存储过程:-

ALTER PROCEDURE dbo.deleteuserclass
@userid nvarchar(50),
@classid int
AS
Begin

Delete from Users_Classes where UserID = @userid AND ClassID = @classid
END

如果存储过程没有删除任何记录,我如何将异常传递给将在数据库端引发的操作方法?

编辑:-我更新存储过程如下:-

ALTER PROCEDURE dbo.deleteuserclass
@userid nvarchar(50),
@classid int
AS
Begin

Delete from Users_Classes where UserID = @userid AND ClassID = @classid
if @@rowcount = 0
Raiserror('No record deleted',1,16)
END

我更新了操作方法:-

        public ActionResult Delete(string id, int classid ) {
try{
Thread.Sleep(1000);
Users_Classes u_c = r.FindUserClass(id, classid);
r.Deleteuserclass(id, classid);
return Json(new { IsSuccess = "True", id = u_c.UserID + u_c.AddedDate.ToString("ddMMyyyyHHmmss"), name = u_c.UserID }, JsonRequestBehavior.AllowGet);
}
catch (ArgumentNullException)
{
return Json(new { IsSuccess = "F1" }, JsonRequestBehavior.AllowGet);}
catch (DbUpdateConcurrencyException)
{return Json(new { IsSuccess = "F2" }, JsonRequestBehavior.AllowGet); }
catch (NullReferenceException)
{return Json(new { IsSuccess = "F4" }, JsonRequestBehavior.AllowGet); }
catch (Exception e)
{return Json(new { IsSuccess = "F5" }, JsonRequestBehavior.AllowGet);}

但问题是,如果存储过程没有删除任何记录,那么应用程序将在 return Json(new { IsSuccess = "True", id = u_c.UserID + u_c.AddedDate.ToString("ddMMyyyyHHmmss"), name = u_c.UserID }, JsonRequestBehavior.AllowGet); ,它不会引发应该已经在存储过程级别引发的异常'No record deleted', 在到达 return 语句之前.. 那么可能是什么问题?

最佳答案

您要做的是传递不规则的存储过程的返回值。你会像这样修改你的存储过程:

ALTER PROCEDURE dbo.deleteuserclass
@userid nvarchar(50),
@classid int
AS
Begin

Delete from Users_Classes
where UserID = @userid
AND ClassID = @classid

if @@rowcount = 0
return -1

END

我不确定您是如何调用存储过程的(对 EF 不太熟悉),但您应该能够捕获返回值:

// notice this method now returns bool instead of void
public bool Deleteuserclass(string a, int u)
{
return entities.deleteuserclass(a,u) > 0;
}

然后在您的 POST 操作方法中,只需测试 DeleteUserClass() 方法的 bool 结果:

[HttpPost]
public void Delete(string id, int classid )
{
if (!repository.Deleteuserclass(id, classid))
// no user deleted, handle accordingly
}

关于asp.net-mvc-3 - 如何将异常从存储过程传递到我的 Post Action 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9712819/

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