曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
C#

Using ODP.NET Core + Dapper to Operate Oracle Databases in .NET Core (C#)

Preface Although people have long talked about “de-IOE,” in state-owned enterprises and government, Oracle’s historical baggage is simply too heavy—even a lot of business logic is implemented inside various Oracle stored procedures… Our systems’ main tech stack is Django / Spring / AspNetCore. Needless to say, Java’s support for Oracle is definitely no problem; the key issue is that Django has Oracle version requirements and compatibility isn’t particularly good, and Oracle versions can’t be upgraded at will, so I thought of using .Net

曦远 (DealiAxy)约 14 分钟
目录5 个章节

Preface

Although people have long talked about “de-IOE,” in state-owned enterprises and government, Oracle’s historical baggage is simply too heavy—even a lot of business logic is implemented inside various Oracle stored procedures…

Our systems’ main tech stack is Django / Spring / AspNetCore. Needless to say, Java’s support for Oracle is definitely no problem; the key issue is that Django has Oracle version requirements and compatibility isn’t particularly good, and Oracle versions can’t be upgraded at will, so I thought of writing a middle layer in .NET Core so that other systems can conveniently use Oracle data and stored procedures…

ODP.NET Core is an ADO.NET driver that provides fast data access from Microsoft .NET Core clients to Oracle Database. It can run on Windows and Linux. ODP.NET consists of a 100% managed-code dynamic-link library, Oracle.ManagedDataAccess.dll, available via NuGet.

This Oracle.ManagedDataAccess.Core is really convenient—no need to install an Oracle client. Compatibility, convenience—anyway, it’s out of the box; just go all in and you’re done.

Simple Usage

First install this Oracle.ManagedDataAccess.Core with NuGet, then you can perform all kinds of operations. Looking at the amount of code, though, it’s still rather tedious. Here’s the code:

var connStr = $"DATA SOURCE=127.0.0.1/db_name; PASSWORD=password; PERSIST SECURITY INFO=True; USER ID=user_id";
using (var conn = new OracleConnection(connStr)) {
    using (var command = conn.CreateCommand()) {
        try {
            if (conn.State == ConnectionState.Closed) {
                conn.Open();
            }

            command.BindByName = true;
            command.CommandText = $"select * from table_name";

            using (var reader = command.ExecuteReader()) {
                while (reader.Read()) {
                    Console.WriteLine(reader.GetString("DEPART_NAME"));
                }
            }
        }
        catch (Exception ex) {
            Console.WriteLine(ex.StackTrace);
            Console.WriteLine(ex.Source);
            Console.WriteLine(ex.Message);
        }
    }
}

This is the code to execute the SQL statement select * from table_name. A bit long…… ugh

Now look at executing a stored procedure…

var connStr = $"DATA SOURCE=127.0.0.1/db_name; PASSWORD=password; PERSIST SECURITY INFO=True; USER ID=user_id";
using (var conn = new OracleConnection(connStr)) {
    conn.Open();
    var command = new OracleCommand("proc_name", conn) {
        CommandType = CommandType.StoredProcedure
    };

    // 输入参数
    command.Parameters.Add(new OracleParameter("id", "0001"));

    // 输出参数
    var vOut = new OracleParameter("v_out",
        OracleDbType.Varchar2,
        1000,
        "",
        ParameterDirection.InputOutput
    );

    command.Parameters.Add(vOut);

    var affectRows = command.ExecuteNonQuery();

    Console.WriteLine(vOut.Value);
}

Here I removed the error handling so it looks a bit shorter, but it’s still terribly cumbersome……

So here we’ll use Dapper, this lightweight ORM, to simplify operations.

Using Dapper

Not much to say—first, installing via NuGet is the usual drill; the package name is simply Dapper.

First, ordinary SQL statements like CRUD:

using Dapper;

var connStr = $"DATA SOURCE=127.0.0.1/db_name; PASSWORD=password; PERSIST SECURITY INFO=True; USER ID=user_id";
using var cn = new OracleConnection(connStr);

var result = cn.Query("select * from table_name");

foreach (var item in result) {
    Console.WriteLine(item);
}

You can see that after introducing Dapper, you just use the OracleConnection extension method Query to execute SQL~ The returned result is of type IEnumerable<dynamic>. Of course you can also specify the return type in the generic parameter of the Query method; I don’t specify it here for generality.

Continuing with stored procedures—very simple, pretty much the same as above, just one extra parameter to tell the program what our SQL type is.

var connStr = $"DATA SOURCE=127.0.0.1/db_name; PASSWORD=password; PERSIST SECURITY INFO=True; USER ID=user_id";
using var cn = new OracleConnection(connStr);

var result = cn.Query("proc_name", commandType: CommandType.StoredProcedure);

foreach (var item in result) {
    Console.WriteLine(item);
}

What if it’s a stored procedure with parameters?

Very simple (code from the official example)~

var user = cnn.Query<User>("spGetUser", new {Id = 1},
        commandType: CommandType.StoredProcedure).SingleOrDefault();

ok, very convenient. For more operations, just look at the Dapper docs and you’re done (this is also my first time using Dapper; I used FreeSQL and EFCore before). That’s the end of this article~

Dapper project homepage: https://github.com/StackExchange/Dapper

References

Welcome to Discuss

Programming Lab focuses on exploring popular new internet technologies and team agile development practices. Reply with linux, flutter, c#, netcore, android, kotlin, java, python, etc. in the backend of the WeChat official account “程序设计实验室” to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~

_EOF_

Using ODP.NET Core + Dapper to Operate Oracle Databases in .NET Core (C#)

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

C#学习(三)深入理解委托、匿名方法和-Lambda-表达式

前言 lambda的概念建立在委托的基础上,委托,实现了类型安全的回调方法。在.NET 中回调无处不在,所以委托也无处不在,事件模型建立在委托机制上,Lambda 表达式本质上就是一种匿名委托。本文中将完成一次关于委托的旅行,全面阐述委托及其核心话题,逐一梳理委托、委托链、事件、匿名方法和 Lambda 表达式。 委托的定义 了解委托,从其定义开始,通常一个委托被声明为: public deleg

2021-12-18 · C# · 约 1 分钟

SharpIco:用纯C#打造零依赖的.ico图标生成器,支持.NET9与AOT编译

SharpIco 是一款纯 C# 实现的跨平台图标生成工具,支持 AOT 编译,无需外部依赖。它能将 PNG 图片分解为多尺寸(16x16至512x512)合成 ICO 图标,并支持图标结构分析。工具提供命令行界面,可通过 dotnet tool 一键安装,并已发布至 NuGet 和 Scoop。项目旨在简化图标生成与验证,追求轻量、纯粹、易集成的使用体验。

2025-05-26 · C# · 约 1 分钟

C#实现解析Markdown文档并处理图片链接

前言 又是好久没写博客了 其实也不是没写,是最近在「做一个博客」,从2月21日开始,大概一个多星期的时间,疯狂刷进度,边写代码边写了一整系列的博客开发笔记,目前为止已经写了16篇了,然后上3月之后工作有点忙~~加上有点沉迷原神~~,然后进度就暂时慢下来了 事实证明做什么事情一旦停下来就会产生惰性,于是停了这么久,我终于下定决心继续更新! 这次开发的博客用的是C#语言,搭配.netcore技术栈;前

2022-03-19 · C# · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…