Exemplo n.º 1
0
 // Managing Entity Framework database connection with C# keyword using.
 // On compilation using is rewriten into try/finally shown below.
 private static List <Post> GetAllPostsFromDB()
 {
     using (var context = new PostsContext())
     {
         return(context.Posts.ToList());
     }
 }
Exemplo n.º 2
0
        // Managing database connection with try/catch/finally
        private static List <Post> GetAllPostsFromDBTryFinally()
        {
            PostsContext context = null;

            try
            {
                // in case of fail the DBContext will be disposed in finally block
                context = new PostsContext();
                return(context.Posts.ToList());
            }
            catch (SqlException exception)
            {
                // Log exception
                throw;
            }
            finally
            {
                if (context != null)
                {
                    // DBContext implements IDisposable and must be manually disposed
                    ((IDisposable)context).Dispose();
                }
            }
        }