HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Connecting to Oracle using ODP.NET

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
connectingodpnetusingoracle

Problem

What can be improved in my code:

using (var oracleConnection = new OracleConnection(ConnectionString))
        {
            using (var oracleCommand = oracleConnection.CreateCommand())
            {
                oracleConnection.Open();

                oracleCommand.CommandText = 
                "SELECT * 
                 FROM table_sample Table_Sample 
                 WHERE table_sample.id > 1000";

                using (var reader = oracleCommand.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        int id = reader.GetValue(0);
                    }
                }
            }
        }


As the most "dangerous" thing I see the ugly string statement for database query.

I dont want to use Entity Framework for Oracle - cause its not as actual as one for MS SQL Server. And also some Oracle features are not supported.

Solution

You're using using blocks to dispose your disposables, which is excellent. However these blocks increase the nesting of your code; since there's nothing between using (var oracleConnection = new OracleConnection(ConnectionString)) and using (var oracleCommand = oracleConnection.CreateCommand()) you could drop the curly braces and "stack" them, like this:

using (var oracleConnection = new OracleConnection(ConnectionString))
    using (var oracleCommand = oracleConnection.CreateCommand())
    {
        ...
    }


Within that scope, you're reassigning variable Id at each row that gets read; ultimately the value of Id will be that of the last row that was read. I doubt this is the intended behavior.

As for the string query, I agree it's "dangerous" - I prefer (by far) to use an object-relational mapper such as Entity Framework (which as @svick has mentioned has an Oracle provider), but never used it for anything other than SQL Server. I believe you could look into NHibernate as well, or shop around - something like ".net ORM for oracle" should find you some interesting links :)

Code Snippets

using (var oracleConnection = new OracleConnection(ConnectionString))
    using (var oracleCommand = oracleConnection.CreateCommand())
    {
        ...
    }

Context

StackExchange Code Review Q#36687, answer score: 5

Revisions (0)

No revisions yet.