在.NET開發面向Oracle資料庫的應用程式

來源:互聯網
上載者:User

標籤:

其實這個不是一個什麼新的話題。但是之前在多次項目中,總是遇到大家針對Oracle資料庫的訪問時,會有各種各樣的問題,最基本的就是要在用戶端安裝各種client,版本不一樣的話還有各種問題。

靜下心來看看,其實也沒有那麼難。我這裡總結一下,如何在.NET應用程式中,簡單優雅地使用Oracle資料庫。

第一個原則:不要依賴

最好的情況就是,程式自己就可以完成資料訪問,不需要額外地安裝所謂的Oracle Client,那是一個很麻煩而且痛苦的事情。

我們首先看看,如果不裝任何東西,是否可以實現Oracle資料庫訪問?

其實,.NET本身是內建了針對Oracle資料庫訪問的組件的,就是下面這個System.Data.OracleClient

我們的代碼如下(這是最原始的ADO.NET代碼,只是做示範)

using System;
using System.Data.OracleClient;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var connectionString = "user id=system;password=password;data source=192.168.56.101:1521/orcl";

            using (var connection = new OracleConnection(connectionString))
            {
                var cmd = connection.CreateCommand();
                cmd.CommandText = "select * from sys.dba_all_tables";
                connection.Open();
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetString(0));

                }

                reader.Close();
                connection.Close();

            }
           
        }
    }
}

 

看起來應該是沒有問題的,運行起來卻會報錯

Additional information: System.Data.OracleClient requires Oracle client software version 8.1.7 or greater.

這裡的提示就是說,需要有Oracle Client。

這不是我們希望看到的結果。實際上原理上說,我們這麼理解吧,可能是這個組件只是一個wrapper,它實際去操作資料庫,還需要通過Oracle Client才能實現。

 

使用Oracle提供的組件

更好的建議就是,使用Oracle 官方提供的Managed 程式碼組件。Oracle.ManagedDataAccess.dll

只要添加了這個Nuget Package,代碼幾乎不需要任何改動,直接就可以複用。

using System;
using Oracle.ManagedDataAccess.Client;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var connectionString = "user id=system;password=password;data source=192.168.56.101:1521/orcl";

            using (var connection = new OracleConnection(connectionString))
            {
                var cmd = connection.CreateCommand();
                cmd.CommandText = "select * from sys.dba_all_tables";
                connection.Open();
                var reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.GetString(0));

                }

                reader.Close();
                connection.Close();

            }
           
        }
    }
}

 

當然比較理想的情況是將連接字串之類的,可以放在設定檔中去。這個很簡單,這裡就不說明了。

 

結合Entity Framework使用

Entity Framework 出來已經好多年了,幾乎成了所有.NET應用程式中的標配(不管有沒有用到)。現在的最新版本應該是 6.1.3 .同時,需要注意的是,以後會有一個所謂的Entity Framework Core ,而且開源了 https://github.com/aspnet/EntityFramework

回到正題,之前的代碼寫法其實還是比較原始的,那麼如何結合Entity Framework進行Oracle資料庫方面的編程呢?

首先,安裝下面的這個組件:Oracle.ManagedDataAccess.EntityFramework

然後,可以使用Code first的方式編寫如下代碼

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;

namespace ConsoleApplication
{
    public class OracleContext : DbContext
    {
        public OracleContext() : base("OracleDbContext")
        {

        }

        public DbSet<Employee> Employees { get; set; }

    }

    [Table("EMPLOYEES", Schema = "SYSTEM")]
    public class Employee
    {
        [Key()]
        [Column("EMPLOYEEID")]
        public int EmployeeID { get; set; }

        [Column("FIRSTNAME")]
        public string FirstName { get; set; }
        [Column("LASTNAME")]
        public string LastName { get; set; }
    }
}

 

 

這裡的代碼沒有什麼出奇的。設定檔需要有如下的設定(一般在添加Oracle.ManagedDataAccess.EntityFramework 這個組件的時候,會自動修改設定檔)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <oracle.manageddataaccess.client>
    <version number="*">
      <dataSources>
        <dataSource alias="oracle" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.56.101)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=ORCL))) " />
             </dataSources>
    </version>
  </oracle.manageddataaccess.client>
  <connectionStrings>
    <add name="OracleDbContext" connectionString="user id=system;password=password;data source=oracle" providerName="Oracle.ManagedDataAccess.Client" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <remove invariant="Oracle.ManagedDataAccess.Client" />
      <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
  </system.data>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <publisherPolicy apply="no" />
        <assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
        <bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="v13.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

後台資料庫的表格設計也是很簡單。

需要注意的是,經過實驗,我發現目前這個Entity Framework要求所操作的表必須要有主鍵,而且主鍵必須是一個identity column(即自己綁定一個序列,實現自動成長),否則會報錯

實際上後台會通過一個觸發器來實現這個功能

create or replace TRIGGER EMPLOYEES_TRG
BEFORE INSERT ON EMPLOYEES
FOR EACH ROW
BEGIN
  <<COLUMN_SEQUENCES>>
  BEGIN
    IF INSERTING AND :NEW.EMPLOYEEID IS NULL THEN
      SELECT EMPLOYEES_SEQ.NEXTVAL INTO :NEW.EMPLOYEEID FROM SYS.DUAL;
    END IF;
  END COLUMN_SEQUENCES;
END;

 

接下來在前端程式中就簡單多了,下面是一個程式碼片段

var ctx = new OracleContext();

ctx.Employees.Add(new Employee() {FirstName = "ares", LastName = "chen" });
ctx.SaveChanges();

var query = ctx.Employees.ToArray();
foreach (var item in query)
{
    Console.WriteLine(item);
}

 

需要注意的是,如果需要使用Entity Frmaework的Database first或Model first的功能,還是需要安裝Oracle Client,或者準確地說應該是ODAC組件

http://www.oracle.com/technetwork/developer-tools/visual-studio/downloads/index.html

在.NET開發面向Oracle資料庫的應用程式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.