在ASP.NET MVC中,有没有从MySQL查询的简单方法?

时间:2018-10-03 23:42:53

标签: c# mysql asp.net-mvc

当前要查询我的用户表,我必须在控制器中执行以下操作。

using (MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["test_schema"].ConnectionString))
{
    connection.Open();
    MySqlCommand command = new MySqlCommand("SELECT * FROM users", connection);
    MySqlDataReader reader = command.ExecuteReader();

    List<string> users = new List<string>();

    while (reader.Read())
    {
       users.Add(reader["id"] + "\t" + reader["first_name"]);
    }

    ViewBag.users = users;
    reader.Close();
}

在C#中是否可以将结果放入类似于ViewBag的动态对象中? 我在Node.js Express上有一些经验,并使用sequelize模块编写查询,我所要做的就是编写类似

的内容
Sequelize.query("SELECT * FROM users", { type: sequelize.QueryTypes.SELECT }).then(users => {
    // users attributes will be the columns of the user table
});

我省略了如何顺序连接数据库的部分,但是我认为这与问题无关。

1 个答案:

答案 0 :(得分:3)

使用Dapper可以很容易地做到这一点。它支持将数据行反序列化为常规C#类或dynamic对象。

using (MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["test_schema"].ConnectionString))
{
    // the 'Query' method is provided by Dapper
    var users = connection.Query("SELECT id, first_name FROM users");
    // each object in 'users' will have .id and .first_name properties
    ViewBag.users = users;


    // to duplicate your sample code's behaviour of creating strings:
    var users = connection.Query("SELECT id, first_name FROM users")
        .Select(x => string.Concat(x.id, "\t", x.first_name))
        .ToList();
}

或者,您可以反序列化为已经定义的类型:

class User
{
    public string Id { get; set; }
    public string FirstName { get; set; }
}

// here I use 'as FirstName' to change the retrieved column name so I
// can use "normal" C# property names on my User class
var users = connection.Query<User>("select id, first_name as FirstName from users");