在asp.net mvc中有没有更简单的方法从mysql进行查询?

kokeuurv  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(347)

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

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
});

我在sequelize中遗漏了如何连接数据库的部分,但我认为这与问题无关。

gcmastyq

gcmastyq1#

这可以很容易地完成与潇洒。它支持将数据行反序列化为常规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");

相关问题