HorseKing
HorseKing

Reputation: 450

SQLException for Entity Framework

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

Upvotes: 0

Views: 1348

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

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.

Upvotes: 1

Related Questions