C#读取MySql int字段返回错误的数字

时间:2019-05-27 10:46:22

标签: c# mysql asp.net-mvc

我正在使用C#MVC5和MySQL编写网页,当我从int字段请求数字时,MySQL总是返回错误的数字,我找不到解决方案。

MySQL之类的

| Id | Type | Level | Parent_id |ChildrenCount |
| 1  | T    | 1     | 1         |3             |
| 2  | SC   | 2     | 1         |2             |
| 3  | SH   | 3     | 2         |1             |
| 4  | TK   | 4     | 3         |0             |
...

我可以使用sql正常显示它们。

但是C#不能。

下面是C#代码。

public Item GetItem(int id, int level, int pos)
{
    Item item = new Item { Id = -1 };

    using (MySqlConnection con = new DBConnect().MySql())
    {
        string sql = $"SELECT * FROM item WHERE Parent_id={id} AND Level={level} LIMIT {pos}, 1;";
        using (MySqlCommand cmd = new MySqlCommand(sql, con))
        {
            con.Open();
            MySqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                item.Id = reader.GetInt32(0);
                item.Type = reader.GetString(1);
                item.Level = reader.GetInt32(2);
                item.ChildrenCount = reader.GetInt32(3);
            };
        }
    }
    return item;
}
public void GetItemList(int id, int level, int count, ref List<Item> pli, int initPos=0)
{
    int pos = 0;
    pos += initPos;
    Item item = GetItem(id, level, pos);

    if (item.Id == -1)
    {
        return;
    }

    pli.Add(item);

    // Here item.Level is wrong.

    if (pli.Count() < count)
    {
        if (item.ChildrenCount > 0)
        {
            int ChildPos = 0;
            int newLevel = item.Level + 1;
            GetItemList(item.Id, newLevel, count, ref pli, ChildPos);
        }
        else
        {
            int newPos = pos + 1;
            GetItemList(id, level, count, ref pli, newPos);
        }
    }
}

致电

public List<Item> GetInitItem(int id)
{
    List<Item> resItemList = new List<Item> { };
    GetItemList(id, level: 1, count: 50, pli: ref resItemList, initPos: 0);

    return resItemList;
}

其他信息都可以,只有“级别”列是错误的,都返回1。

结果显示在页面上

ID:6133   Type:T   Level:1   Count:744   
ID:6154   Type:SC   Level:1   Count:67 

0 个答案:

没有答案