2017-08-30 80 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