将数据库表传输到 类/ 类 到数据库表

Transferring database tables to Classes/ Classes to database tables

这是我要求的更详细的示例问题:

我将 c# 与 Sql 服务器一起使用,并将 Dapper 用作我的 ORM。

这是我的 table:

这是我的 class,它将组件 table 加载到应用程序中:

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 将具有实际值:

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" Class 将有一个方法,该方法将采用 "Component" 对象并创建一个 "DBComponent" 对象,该对象将作为新记录发送回数据库。

这是处理这种情况的最佳方式吗?或者有更好的方法吗?在我的另一个 post 中,有人提到 dapper 可以自行完成此操作,我不需要创建 2 classes,只需要 1 class。怎么会这样?

您可以只使用一个 class 和一个查询来加载您的数据。只需构建正确的 sql 查询并让 Dapper 在将检索到的数据映射到您的组件 class.

中施展魔法

假设您像这样更改组件 class

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,因为成员名称不能与封闭类型同名