我是asp.net和sql server的新手我写了一个代码来设置我的模型,我只需要一行,所以我写了这段代码:
我的模特
public class FullPackages
{
public int Id { get; set; }
public int TypeId { get; set; }
[Display(Name = "Package Type")]
public string TypeName { get; set; }
public int AllowedSMS { get; set; }
[Display(Name = "Time Span in Days")]
public int? TimeSpan { get; set; }
public decimal Price { get; set; }
}
我的方法
public ActionResult PackageDetails(int id = 0)
{
string sqlString = "select top 1 tblPackages.*, tblPackageTypes.Name from tblPackages join tblPackageTypes on tblPackages.TypeId = tblPackageTypes.Id where tblPackages.Id = "+id;
SqlConnection con = new SqlConnection(cnxn); // cnxn is defined
SqlCommand cmd = new SqlCommand(sqlString, con);
SqlDataReader dsr;
FullPackages package = new FullPackages();
con.Open();
dsr = cmd.ExecuteReader(); // this returns null value
package.Id = dsr.GetInt32(0);
package.TypeId = dsr.GetInt32(1);
package.TypeName = dsr.GetString(5);
package.AllowedSMS = dsr.GetInt32(2);
package.TimeSpan = dsr.IsDBNull(3) ? 0 : dsr.GetInt32(3);
package.Price = dsr.GetDecimal(4);
con.Close();
return View(package);
}
当我从sqlString中删除top 1
时,它返回数据库中的值但是当我保留top 1
时它返回null。当我在sql server中检查与top 1
相同的sql时Mgmt Studio它返回单行..为什么会这样?请帮帮我......
答案 0 :(得分:1)
您可以执行以下操作而不是代码:
string sqlString = "select top 1 tblPackages.*, tblPackageTypes.Name from tblPackages join tblPackageTypes on tblPackages.TypeId = tblPackageTypes.Id where tblPackages.Id = " + id;
SqlConnection con = new SqlConnection(cnxn); // cnxn is defined
SqlDataAdapter sda = new SqlDataAdapter(sqlString, con);
DataTable dt = new DataTable();
sda.Fill(dt);
FullPackages package = new FullPackages();
package.Id = Convert.ToInt32(dt.Rows[0][0]);
package.TypeId = Convert.ToInt32(dt.Rows[0][1]);
package.AllowedSMS = Convert.ToInt32(dt.Rows[0][2]);
package.TimeSpan = !DBNull.Value.Equals(dt.Rows[0][3]) ? Convert.ToInt32(dt.Rows[0][3]) : 0;
package.Price = Convert.ToInt32(dt.Rows[0][4]);