2017-08-30 54 views
1

這是一個更詳細的例子問題,我問:Best Practice with classes and the database傳輸數據庫表類/類到數據庫表

我使用C#與SQL Server和使用小巧玲瓏作爲我的ORM。

這裏是我的表: enter image description here

這裏是我的類,將組件表加載到應用程序:

class DBComponent 
{ 
    public int ID { get; set; } 
    public string Component { get; set; } 
    public int Material_ID { get; set; } 
    public int Color_ID { get; set; } 
} 

然後,我需要我的其他類,將具有實際值:

class Component 
{ 
    public int ID { get; set; } 
    public string Component { get; set; } 
    public string Material { get; set; } 
    public string Color { get; set; } 

    public Component(DBComponent C) 
    { 
     ID = C.ID; 
     Component = C.Component; 
     Material = //queries the Material Table passing in C.Material_ID and returning the Material Value 
     Color = //queries the Color Table passing in C.Color_ID and returning the Color Value 
    } 
} 

我這樣做的原因是,我可以使用控件(組合框)的WinForm應用程序的值,和其他需求。此外,「DBComponent」類將具有一個方法,該方法將採用「Component」對象並創建一個「DBComponent」對象,該對象將作爲新記錄發送回數據庫。

這是處理這種情況的最好方法嗎?還是有更好的方法?在我的另一篇文章中有人提到,小巧玲瓏可以自己做到我不需要創建2個類的地方,只需要1個類。這是怎麼回事?

+0

您可以使用隱式運算符來執行此操作。看看這裏:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/implicit – Egbert

+0

@Egbert我可以看到如何使用隱式可以在這裏使用,我不認爲我我會在這種情況下使用它,但我喜歡這個概念,我會在我的項目的其他部分使用它,謝謝! – jediderek

回答

1

您可以只使用一個類和一個查詢來加載數據。建立正確的sql查詢只是一個問題,並且讓Dapper在將檢索到的數據映射到您的Component類時發揮它的魔力。

假設你改變你的組件類這樣

public class Component 
{ 
    public int ID { get; set; } 
    public string ComponentX { get; set; } 
    public int Color_ID { get; set; } 
    public int Material_ID { get; set; } 
    public string Material { get; set; } 
    public string Color {get;set;} 
} 

現在你可以使用表之間的適當加入

IEnumerable<Component> SelectComponents() 
{ 
    using (IDbConnection connection = OpenConnection()) 
    { 
     const string query = @"SELECT p.ID, p.Component as ComponentX, 
             p.Color_ID, p.Material_ID, 
             c.Color, m.Material 
           FROM Component p 
           JOIN Color c on p.Color_ID = c.ID 
           JOIN Material m on p.Material_ID = m.ID"; 

     return connection.Query<Component>(query, null); 
    } 
} 

注意,我已改名爲成員的Component ComponentX檢索您的數據,因爲你不能有一個與封閉類型名稱相同的成員名稱

+0

因此,從技術上講,我不需要在該類的查詢中使用Color_ID和Material_ID。 – jediderek

+0

不,如果你喜歡,你可以避開它們,但是將它們用於未來用途並不會傷害。當然,你不會向用戶顯示這些值,但這只是你的UI界面的一個問題。 – Steve

+0

完美!我感謝你的幫助,這比我想象的要容易得多。這一切都取決於查詢。謝謝! – jediderek