前言

使用 Access 主要原因是為了做小型專案減少開發才會使用的一個DB 環境,廣泛性不大但是可以做簡單的系統,可以使用看看。

創建 AccessContext

前期可以得之 EF 通常都是用在Ms SQL 、My SQL 等載入,若要達到建議版本可以參考下方做法。

取得連線字串

驅動方式可以參考 : 【Microsoft】

1
2
3
4
5
6
public AccessContextcs()
{
string connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=D:\\Git\\Github\\00_Source\\ng-homestay\\WebApi\\lanyuanApi\\DbContext\\AccessUsers.accdb; ";
Connection = new OdbcConnection(connectionString);
}

製作相關Table

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public IEnumerable<Information> InformationData()
{
var queryText = "SELECT * FROM Information";
var data = Connection.Query<Information>(queryText);
return data.AsEnumerable();
}

public IEnumerable<BasicUserAccess> BasicUserAccessonData()
{
var queryText = "SELECT * FROM BasicUserAccess";
var data = Connection.Query<BasicUserAccess>(queryText);
return data.AsEnumerable();
}
public IEnumerable<Introduction> IntroductionData()
{
var queryText = "SELECT * FROM Introduction";
var data = Connection.Query<Introduction>(queryText);
return data.AsEnumerable();
}

整體程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
using Dapper;
using lanyuanApi.Models;
using System.Data.Odbc;

namespace lanyuanApi.DbContext
{
public class AccessContextcs
{
public OdbcConnection Connection { get; set; } = default!;
public AccessContextcs()
{
string connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=D:\\Git\\Github\\00_Source\\ng-homestay\\WebApi\\lanyuanApi\\DbContext\\AccessUsers.accdb; ";
Connection = new OdbcConnection(connectionString);
}

public IEnumerable<Information> InformationData()
{
var queryText = "SELECT * FROM Information";
var data = Connection.Query<Information>(queryText);
return data.AsEnumerable();
}

public IEnumerable<BasicUserAccess> BasicUserAccessonData()
{
var queryText = "SELECT * FROM BasicUserAccess";
var data = Connection.Query<BasicUserAccess>(queryText);
return data.AsEnumerable();
}
public IEnumerable<Introduction> IntroductionData()
{
var queryText = "SELECT * FROM Introduction";
var data = Connection.Query<Introduction>(queryText);
return data.AsEnumerable();
}
}
}