.Net Core連結Oracle 及建立 DbContext
若要在使用 .NET 的專案中連接 Oracle 資料庫,你可以使用 Oracle 官方提供的 Oracle Data Provider for .NET (ODP.NET)。這個函式庫支援 Entity Framework Core 以及傳統的 ADO.NET 方法。以下是使用 ODP.NET 連線 Oracle 資料庫的一些基本步驟:
安裝 ODP.NET
首先,需要新增 ODP.NET 的 NuGet 套件到你的專案中。最常用的套件是 Oracle.ManagedDataAccess.Core(適用於 .NET Core 專案)和 Oracle.EntityFramework.Core(適用於 Entity Framework Core)。
使用命令列工具安裝這些套件:
dotnet add package Oracle.ManagedDataAccess.Core
dotnet add package Oracle.EntityFrameworkCore
{
"ConnectionStrings": {
"OracleDB": "User Id=your_user_id;Password=your_password;Data Source=your_data_source;"
} }
- User Id 是你的資料庫使用者名稱。
- Password 是你的密碼。
- Data Source 是 Oracle 服務的名字,通常是 TNS 名稱或是 Easy Connect 名稱(例如:myserver:1521/mydatabase)。
2.配置 DbContext:
在 Startup.cs
或在 .NET 6 及以后版本的 Program.cs
中配置你的 DbContext 使用 Oracle 提供者:
對於 .NET 5 先前的版本,在 Startup.cs 中:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<YourDbContext>(options =>
options.UseOracle(Configuration.GetConnectionString("OracleDB")));
}
- 對於 .NET 6 及之後的版本,在 Program.cs 中:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddDbContext<YourDbContext>(options =>options.UseOracle(builder.Configuration.GetConnectionString("OracleDB")));var app = builder.Build();
測試連接
注意事項
在.NET中使用YourDbContext這個名稱時,它通常是代表你應用中與資料庫操作相關的一個類,這個類繼承自DbContext。 DbContext是Entity Framework Core的一部分,是用於與資料庫互動的主要類,它管理實體物件的生命週期,包括從資料庫讀取資料、更改追蹤以及保存資料到資料庫。
一、建立自訂的 DbContext
當看到YourDbContext,這意味著你需要根據自己的應用需求定義一個類,這個類繼承自DbContext。下面是如何定義這樣一個DbContext類別的基本步驟:
1.定義 DbContext 類別: 在專案中建立一個新的類別文件,命名為YourDbContext.cs(或任何其他喜歡的名字),然後定義類別並使其繼承自DbContext。這個類別中將包含資料庫表對應的DbSet屬性。
using Microsoft.EntityFrameworkCore;
public class YourDbContext : DbContext
{
public YourDbContext(DbContextOptions<YourDbContext> options)
: base(options)
{
}
// 定義DbSet屬性來對應資料庫表
public DbSet<Product> Products { get; set; }
// 可以加入更多的DbSet來映射其他表
}
需要根據實際的資料庫表結構來定義它和其他類別。
2.定義模型類別: 模型類別是普通的C#類,它們定義了與資料庫表格對應的資料結構。例如,如果有一個名為"Products"的表,可以建立一個名為Product的類別來映射這個表的結構:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
// 其他与数据库表字段对应的属性
}
3.設定 DbContext 使用資料庫: 在你的應用程式的啟動類別中(例如Startup.cs或Program.cs),需要設定服務來使用定義的DbContext,如先前提到的使用Oracle資料庫的設定方式。
留言
張貼留言