我有下面的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);}
但问题是如果存储过程没有删除任何记录,那么应用程序将在NullReferenceException
上引发后续异常return Json(new { IsSuccess = "True", id = u_c.UserID + u_c.AddedDate.ToString("ddMMyyyyHHmmss"), name = u_c.UserID }, JsonRequestBehavior.AllowGet);
,并且它不会引发应该已经引发的异常在存储过程级别'No record deleted'
上,在达到return
声明之前.. 那么可能是什么问题?
答案 0 :(得分:4)
您要做的是从存储过程中传递不规则的返回值。您可以修改存储过程,如下所示:
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操作方法中,只测试bool
方法的DeleteUserClass()
结果:
[HttpPost]
public void Delete(string id, int classid )
{
if (!repository.Deleteuserclass(id, classid))
// no user deleted, handle accordingly
}
答案 1 :(得分:0)
将存储过程修改为
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('User Deletion failed',1,16)
END
处理异常并重新抛出存储库方法
public void Deleteuserclass(string a, int u)
{
try{
entities.deleteuserclass(a,u);
}catch(Exception e)
{
throw e;
}
}
最后,将调用方法修改为
public bool Deleteuserclass(string a, int u)
{
try{
return entities.deleteuserclass(a,u) > 0;
}
catch(Exception e)
{
//handle exception
logError(e.Message);
}
}