Reputation: 47
Hi i'm trying to make a reservation page. If someone makes a reservation that date gets saved in the database and will also be showed on their page. The type of the column 'dayid' is date in postgresql. In razor pages C# i used the type DateTime for variable Dayid. I need to convert the dayid value from database to a string. But i don't know how to solve this error: "No overload for method 'ToString' takes 1 arguments" Here is the code
public List<ReservationModel> ShowReservation()
{
var cs = Database.Database.Connector();
List<ReservationModel> res = new List<ReservationModel>();
using var con = new NpgsqlConnection(cs);
{
string query = "Select dayid, locationid FROM reservation";
using NpgsqlCommand cmd = new NpgsqlCommand(query, con);
{
cmd.Connection = con;
con.Open();
using (NpgsqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
res.Add(new ReservationModel { Dayid = dr["dayid"].ToString("MM/dd/yyyy"), Locationid = dr["locationid"].ToString() });
}
}
con.Close();
}
}
return res;
}
Upvotes: 1
Views: 851
Reputation: 1500893
The compile-time type of the NpgsqlDataReader
indexer is just object
, and the object.ToString()
method is parameterless. You need an expression of type DateTime
to call the ToString
overload that you want.
You could cast to DateTime
instead:
while (dr.Read())
{
res.Add(new ReservationModel
{
Dayid = ((DateTime) dr["dayid"]).ToString("MM/dd/yyyy"),
Locationid = dr["locationid"].ToString()
});
}
(Or find the column index and call dr.GetDateTime(...)
.)
However, I'd encourage you to change your model (ReservationModel
) to keep the value as a DateTime
instead of converting it to a string at this point anyway. In general, it's a good idea to keep data in its most natural data type for as much of the time as possible, only converting it to/from text at boundaries.
Upvotes: 5