将数据库表转移到类/类到数据库表

时间:2017-08-30 19:29:16

标签: c# database oop dapper

这是我要求的更详细的示例问题:Best Practice with classes and the database

我正在使用c#与Sql Server并使用Dapper作为我的ORM。

这是我的表格: enter image description here

这是我的类,它将Component表加载到应用程序中:

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”对象,该对象将作为新记录发送回数据库。

这是处理这种情况的最佳方法吗?还是有更好的方法?在我的另一篇文章中,有人提到dapper可以自己做到这一点,我不需要创建2个类,只需要1个类。怎么会这样?

1 个答案:

答案 0 :(得分: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,因为您不能拥有与封闭类型同名的成员名称