开发者

SQLException for Entity Framework

开发者 https://www.devze.com 2023-03-19 04:17 出处:网络
I have a very simple question. I made a Stored Procedure for my SQL and it looks like this: IF(@CurrentStatus=\'Fulfilled\')

I have a very simple question.

I made a Stored Procedure for my SQL and it looks like this:

    IF(@CurrentStatus='Fulfilled')
    BEGIN
        RAISERROR ('Opps, this item is too hot to last too long. It is SOLD OUT!',16, 1)
        RETURN -1           
    END

It will return a error message when the condition is meet.

In my C# code behind, I am using a try-catch 开发者_如何学运维block.

I simply want to display the error message from the above Stored Procedure to the screen. So which exception type I should use?

Here is my code:

            try
        {
            storeDB.AddToBuyingOrders(newOrder);
            storeDB.SaveChanges();
            TempData["Result"] = "Added";
            return View();
        }
        catch (SqlException ex)
        {
            TempData["Result"] = ex.InnerException.Message.ToString();
            return View();
        }


I wonder why do you ask question for that? You could catch Exception put a breakpoint in your code and got the answer within few seconds!!! It even took me less then five minutes to make working example just because I was curious about what problem is there that you don't do it yourselves.

Correct exception type to catch is EntityCommandExecutionException or its parent EntityException. The SqlException will be in its InnerException property and you will get your message there.

0

精彩评论

暂无评论...
验证码 换一张
取 消