如何从两个不同的表返回列值?

时间:2015-04-25 13:45:36

标签: c# database

我正在尝试从数据库表中接收数据,我的sql查询也从另一个表中选择了一个我想要返回的列

          while (dr.Read())
          {
              Inlagg comentsar = new Inlagg
              {
                  names = (int)dr["name"],
                  dates = (DateTime)dr["Date"]
 //get column value from the other table not the Inlagg table here pobbisble?

              };
       //This gets the column value from the other table but i dont know how to return it
              string test = (string)dr["test"];
                  comen.Add(comentsar);

          }
          return comen;

如何返回包含来自不同表的列的列的结果?旁注:我有一个我不需要在这里收到的列,尽管列是一个int而我正在尝试接收一个字符串,有没有办法将列强制转换为字符串?任何帮助或输入高度赞赏,谢谢!

编辑:“解决”它只需创建一个包含我想要的值的新类,其中包含来自不同表的列值

2 个答案:

答案 0 :(得分:1)

在您的读者内部,您遗漏了以下内容:

if(reader["Column"] != DBNull.Value)
     model.Name = reader["Column"].ToString();

您对SQL的查询应正确连接多个表,然后在返回的结果集中,您将返回一个列名。您调用reader["..."]来访问所述列的值。

正如您注意到model类调用属性的名称。

模型很重要,因为它代表您的数据,但要通过阅读器访问,您只需添加另一个属性。

这是因为该列为null,因此您无法强制转换 ToString(),这就是错误发生的原因。您也可以尝试:

int? example = reader["Column"] as int?;

答案 1 :(得分:0)

扩展你的课程:

public class Inlagg{
   ...
   addMyString(String myString){
      this.myString = myString;
   }
   getMyString(){
      return this.myString;
   }
}
相关问题