是否有关于如何从数据库获取数据到对象或模型的良好实践

Is there a good practice on how to fetch data from DB to Objects or Models

我正在设置一个日志,我正在尝试创建一个函数以便稍后使用 HangFire 调用。我要创建的函数将执行以下操作:

查询 Select Timestamp 上的最新行并获取所有列值并将它们引用到我的 LogEntires 模型属性。

在 ADO.NET 中是否有执行此操作的良好做法? return 查询 select 时如何处理 return 类型?

public LogEntries GetEntires(LogEntries entries)
{
    using (var conn = new SqlConnection(ConnectionString))
    using (var cmd = new SqlCommand())
    {
        conn.Open();

        var adapter = new SqlDataAdapter("SELECT TOP 1 *" +
                                          "FROM logTable" +
                                            "ORDER BY LOG_WRITING_TIME desc", conn);
        var dataSet = new DataSet();
        adapter.FillSchema(dataSet, SchemaType.Source, "RadarMF30_log");
        adapter.Fill(dataSet, "logTable");

        DataTable tbl;
        tbl = dataSet.Tables["logTable"];
        var i = 0;
        foreach (var item in tbl.Rows)
        {
            entries.ErrorCode = tbl.Columns[i].ToString(); // ErrorCode must become dynamic. 
        }

    }
}

好的做法是主观的,但正如上面的评论所建议的那样,你最好使用 Dapper 而不是编写所有样板 ADO.NET 代码。

我猜 ErrorCode 应该是一个列表。

示例(未测试)

    public class LogEntries
    {
        public List<string> ErrorCodes { get; set; }
    }

    public LogEntries GetEntries()
    {
        var logEntries = new LogEntries();
        using (var conn = new SqlConnection("YOUR CONNECTION STRING"))
        {
            conn.Open();
            var errorCodes = conn.Query<string>("YOUR SQL", commandType: CommandType.Text);
            logEntries.ErrorCodes = errorCodes.ToList();
        }

        return logEntries;
    }