views:

34

answers:

1

Hi! I'm using linq to entities, and my entity model is sitting on top of MSSQL database.

I'm wondering if linq to entities throws SqlExceptions or not.
In other words, will the below code catch exception successfully if there was a problem connecting to the database?
If it doesn't, what's the best way to handle exceptions when using linq to entities?

        using (MyUserEntities userEntities = new MyUserEntities(connectionString))
        {
            try 
            {
                if (userEntities.Users.Any<User>(userInDB =>
                                                 userInDB.UserName == username))
                    {
                       //Do Something
                    }
                    else
                    {
                       //Do Something else
                    }
            }
            catch(SqlException e)
            {
            }
        }
+1  A: 

Yes it will, If any of the processes in your function causes a problem,

userEntities.Users.Any<User>(userInDB =>
                                             userInDB.UserName == username)

It will throw a cascading exception whitch will be caught.

Altough there is a specific timeout setting for db connections, so sometimes this takes a while.

Why didn't you test it ? you could have found out this answer yourself

Nealv
I'm (blindly) converting some code which is using ADO.NET into code using linq to Entities. I coudn't test it because I could not think of way to generate an SqlException.
Daniel
simple, just change the url of the database to a wrong url and test, or give false authentication, or add a field in the table and don't update your entity model ....
Nealv
I thought MyUserEntities instance would not be created in the first place if I changed the url or give false authentication.
Daniel
just let the entities be generated, and then change the database url
Nealv