iT邦幫忙

0

C# 與 Sqlite 的小問題

Rong 2023-08-01 20:13:051293 瀏覽
  • 分享至 

  • xImage

想請教各位大大小問題

Sqlite撈出來的資料可以自動填充到Class
但是有時候會有些資料需要有兩個資料表
不曉得怎麼做比較會符合

環境
Sqlite 有 Item, Item_Type 兩個資料表

.Item
Item_ID TEXT
Item_Name TEXT
Item_Type_ID TEXT

.Item_Type
Item_Type_ID TEXT
Item_Type_Name TEXT

第一種

public class Item
{
    public string Item_ID { get; set; }
    public string Item_Name { get; set; }
    public string Item_Type_ID { get; set; }
    public string Item_Type_Name { get; set; }
}

//自動填充
Item = Sqlite.Query<Item>("SELECT * FROM Item LEFT JOIN Item_Type ON Item.Item_Type_ID = Item_Type.Item_Type_ID");

第二種

public class Item
{
    public string Item_ID { get; set; }
    public string Item_Name { get; set; }
    public string Item_Type_ID
    {
        get { ...省略 }
        set
        {
            ...省略部分
            
            //自動填充
            this.Type = Sqlite.Query<Item_Type>("SELECT * FROM Item_Type WHERE Item_Type_ID = '" + this.Item_Type_ID + "'")
        }
    }
    public Item_Type Type;
}

public class Item_Type
{
    public string Item_Type_ID { get; set; }
    public string Item_Type_Name { get; set; }
}

//自動填充
Item = Sqlite.Query<Item>("SELECT * FROM Item");

不知道這樣舉例表達是否有清楚
個人感覺第一種方式比第二種好,畢竟不用開開關關頻繁的連線資料庫查詢
但是這樣衍生出了另一個小問題
如果在有些狀態是需要再與Item衍生的時候呢
例如 庫存

public class Warehouse
{
    public string Item_ID { get; set; }
    public string Item_Name { get; set; }
    public string Item_Type_ID { get; set; }
    public string Item_Type_Name { get; set; }
    public int Amount { get; set; }
}

是這樣就以撈出來的資料為主再建立一個Class嗎?

還望各位大大們指教一下!

柯柯 iT邦新手 3 級 ‧ 2023-08-02 16:50:54 檢舉
第一種
Class 可以單純的只負責定義變數 不用設定變數的值 自己覺得後續會比較方便維護 資料的給予都放在其他地方

JOIN TABLE class 用繼承的方式做
public class Item
{
public string Item_ID { get; set; }
public string Item_Name { get; set; }
public string Item_Type_ID { get; set; }
public string Item_Type_Name { get; set; }
}
public class Warehouse : Item
{
public int Amount { get; set; }
}
Rong iT邦新手 5 級 ‧ 2023-08-02 19:30:32 檢舉
對耶!! 我忘記還有繼承的方式了!! 謝謝!!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
bodera
iT邦新手 4 級 ‧ 2023-08-02 16:56:40

主要還是看情況,沒有說一定要使用第一種還是第二種,如你所說'有些狀態是需要再與Item衍生的時候'這種時候我會分開取,有需要再於程式中做JOIN。
而Item與ItemType Join在一起的Class我會命名為View_Item,並且其中會包含Item與ItemType的全部欄位,這樣做的概念其實就是DB中的ViewTable。
再次重申,一切都以當下的商業邏輯怎麼樣區分會邏輯清楚為重,寫Code不能只為了解決問題,還需要考慮到維護的人看不看得懂。

Rong iT邦新手 5 級 ‧ 2023-08-02 19:37:28 檢舉

您說的沒錯! 第一種方式就有點像是Query出來的結果
兩種方式都可以做到我想要的結果,因為後續還有許多資料
所以先以上述兩個資料為例,釐清一些觀念
避免重工!
感謝您的回覆!!

我要發表回答

立即登入回答