Specified cast is not valid exception - c#

This is my code
var result = (from row1 in table.AsEnumerable()
join row2 in tabelPopup.AsEnumerable()
on row1.Field<string>("CallID") equals
row2.Field<string>("callID")
where row1.Field<string>("Direction") == "I"
select new
{
Agent = row1.Field<string>("Agent"),
StartTime = row1.Field<DateTime>("StartTime"),
Reason = row2.Field<string>("Reason")
});
where table and tablePopup are datatable variables.
I got this exception:
Specified cast is not valid
on this code:
new
{
Agent = row1.Field<string>("Agent"),
StartTime = row1.Field<DateTime>("StartTime"),
Reason = row2.Field<string>("Reason")
}

Make sure your column definitions match the type you're using in row1.field<>. i.e. Agent is string, StartTime is datetime and Reason is string. This is likely due to StartTime not being a datetime type.

Probably StartTime is not from Type DateTime. Because of that you receive this exception. Try to convert it. If this is correct you should convert it to DateTime or just retrieve string value.

Related

Unable to cast object of type 'System.DateTime' to type 'System.String'. c#

I'm trying to display the dates and restored it to the Labels = strings,
but I got an error on line list.Add((string)myReader["Date"]);
Here's my code:
con.Open();
myReader = cmdDB.ExecuteReader();
List<string> list = new List<string>();
while (myReader.Read())
{
list.Add((string)myReader["Date"]);
}
string[] strings = list.Select(x => x.ToString()).ToArray();
cartesianChart1.AxisX.Add(new Axis
{
Title = "Date",
Labels = strings
});
cartesianChart1.AxisY.Add(new Axis
{
Title = "Sales",
LabelFormatter = value => value.ToString()
});
Any solution? Thank you! P.S. I'm using LiveCharts and MySQL.
You can try like this
list.Add(myReader["Date"].ToString());
If you want you can also apply formatting to your date in the ToString(dd-MM-yyyy) using Custom Date and Time Format Strings
Do
list.Add(Convert.ToString(myReader["Date"]));
It seems your Datecolumn is not string but a datetime column.
Doing (string)myReader["Date"] tries explicit typecasting on a datetime column to string which is not possible. But Convert.ToString gives the string representation of your value.
Even if the value is null, Convert.ToString(object value) will return null instead of throwing exception like .ToString().
Use
if (Convert.IsDBNull(columnValue))
{
return null;
}
return columnValue;
Ever validate is data is null or emty and return a value
Note: if we have column of type DateTime in DataBase and String in asp.net core/Csharp application
we can convert DateTime to string at store procedure level as
e.g
date_format(ReferralDate, '%d/%m/%Y') as ReferralDate,
Full example of Store procedure
SELECT referralCostsID,
ClientID,
ReferralSource,
date_format(ReferralDate, '%d/%m/%Y') as ReferralDate,
AdCost,
Notes
FROM referralcostssetup

How do i convert Context.User.Identity.GetUserId() to int with c# in asp.net vs2015

How do I convert Context.User.Identity.GetUserId() to an int.
code:
string clientId = Context.User.Identity.GetUserId();
if (clientId != null) {
cart NewInCart = new cart();
NewInCart.ClientId = Convert.ToInt32(clientId);
}
Above code gives error stating:
when converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
I think what you want is:
NewInCart.ClientId = Int32.Parse(clientId);
Sorted for now.
I have decided to change the data type of ClientID in the dbo to nvarchar(50); that way I save like this:
string clientId = Context.User.Identity.GetUserId() ;
.......
cart.ClientId = clientId;
where cart.ClientId is now expecting a string. This sorted my problem and I no longer need to convert Context.User.Identity.GetUserId() to int.

String was not recognized as a valid DateTime - Whats wrong?

I have been getting an annoying littler error and cannot for the life of me figure out why it is being cause. I have an xml file where i am storing data, as shown below.
- <EmployeeFinance>
<EmployeeEmploy_Id>5584</EmployeeEmploy_Id>
<EmpPersonal_Id>30358</EmpPersonal_Id>
<No_DaysWorked>30</No_DaysWorked>
<Date_Appointment>17/02/2012</Date_Appointment>
<Date_Employment>02/05/1984</Date_Employment>
<Date_Termination>01/01/0001</Date_Termination>
<Payperiod_StartDate>01/01/2013</Payperiod_StartDate>
<Payperiod_EndDate>31/01/2013</Payperiod_EndDate>
<BatchNumber>38</BatchNumber>
<PAYE_ToDate_Computed>0</PAYE_ToDate_Computed>
<Income_Tax_RateID>0</Income_Tax_RateID>
<NIS_RateID>0</NIS_RateID>
<NIS_weeks_worked>0</NIS_weeks_worked>
</EmployeeFinance>
If you look at the date nodes, Payperiod_StartDate,Payperiod_EndDate, Date_Appointment etc. They all have the same format. Now in my C# code, when i write my query to select from the xml file i get the String was not recognized as a valid DateTime error. WHen i comment out all the other dates and leave start_date, it works. They are the same format , i cant see what i am doing wrong. Please help me.
var context = new SSPModel.sspEntities();
XElement xelement = XElement.Load(GlobalClass.GlobalUrl);
XDocument doc = XDocument.Load(GlobalClass.GlobalUrl);
var query = from nm in xelement.Elements("EmployeeFinance")
select new EmployeeEmploy
{
Employee_Personal_InfoEmp_id = (int)nm.Element("EmpPersonal_Id"),
Substantive_designation = (int)nm.Element("Position_Id"),
Grade_Id = (int)nm.Element("Grade_Id"),
PositionTotal_PtBasic = (double)nm.Element("Sum_AllPosition"),//part of basic
GradeTotal_PtBasic = (double)nm.Element("Sum_AllGrade"), //part of basic
Housing_Allowance = (double)nm.Element("Housing"),
Base_Pay = (double)nm.Element("Base_Pay"),
startDate = (DateTime)nm.Element("Payperiod_StartDate"),
endDate = (DateTime)nm.Element("Payperiod_EndDate"),
Date_of_Appointment = (DateTime)nm.Element("Date_Appointment"),
Date_of_Employment = (DateTime)nm.Element("Date_Employment"),
Termination_date_actual = (DateTime)nm.Element("Date_Termination"),
Base_Pay_Currency = (string)nm.Element("Currency"),
Exchange_rate = (double)nm.Element("Exchange_Rate")
};
var x = query.ToList();
foreach (var xy in x) {
Debug.WriteLine(xy.endDate);
}
Because 17/02/2012 is not a valid date, however, 02/17/2012 is. The date will be parsed as mm/dd/yyyy. One option is to use DateTime.ParseExact to parse a date with the dd as the first set of numbers. e.g.
var startDate = DateTime.ParseExact("17/02/2012", "dd/MM/yyyy", null);
The debugger will show you that nm.Element("Payperiod_EndDate").ToString() gives you a string that includes the xml tags for that element. Try the following instead:
startDate = DateTime.ParseExact(nm.Element("Payperiod_EndDate").Value, "dd/MM/yyyy", null)

Linq To Data set error System.InvalidCastException: Specified cast is not valid

I get the following exception using Linq to data set "System.InvalidCastException: Specified cast is not valid."
The problem is as follows I have a model with two value of type int?. The values in the database are not required so some fields are blank. I have read the table into a data set and now I need to query the data set using the following code.
//model
public class Model
{
// Public Properties
...
...
...
public int? YearBegin { get; set; }
public int? YearEnd { get; set; }
}
//query
var list = from m in data.Tables["Models"].AsEnumerable()
select new Model
{
// rest of members omitted to simplify
YearBegin = m.Field<int>("YearBegin"),
YearEnd = m.Field<int>("YearEnd")
};
I have tried the following none have worked:
m.Field<int?>("YearBegin")
YearEnd = m.IsNull("YearEnd") ? null, m.Field<int>("YearEnd")
Is there another way to check if the field has a value similar to String.IsNullOrEmpty().
Using string as the type is not a possibility...
Thanks
You aren't using a typed DataSet, so my first question would be is the does the DataTable know that those fields are supposed to be 'int?' in the first place, or are they listed as strings? If the DataTable is treating those fields as strings, you will experience that error. The following code assumes a TestData DataSet with a Models DataRow, with two nullable string columns as YearBegin and YearEnd:
using (TestData ds = new TestData())
{
// Typed Rows
ds.Models.AddModelsRow("1", "2");
ds.Models.AddModelsRow(ds.Models.NewModelsRow()); // NULL INFO TEST
// Untyped rows
DataRow r = ds.Models.NewRow();
r[0] = "4";
r[1] = "5";
ds.Models.Rows.Add(r);
//query
var list = from m in ds.Tables["Models"].AsEnumerable()
select new Model
{
// rest of members omitted to simplify
YearBegin = m.Field<int?>("YearBegin"),
YearEnd = m.Field<int?>("YearEnd"),
};
}
That code will encounter the InvalidCastException. However, when I flip the types on the DataTable to nullable Int32, then the nearly identical code works properly:
using (TestData ds = new TestData())
{
// Typed Rows
ds.Models.AddModelsRow(1, 2);
ds.Models.AddModelsRow(ds.Models.NewModelsRow()); // NULL INFO TEST
// Untyped rows
DataRow r = ds.Models.NewRow();
r[0] = 4;
r[1] = 5;
ds.Models.Rows.Add(r);
//query
var list = from m in ds.Tables["Models"].AsEnumerable()
select new Model
{
// rest of members omitted to simplify
YearBegin = m.Field<int?>("YearBegin"),
YearEnd = m.Field<int?>("YearEnd"),
};
}
Take a look at your DataTable. You can correct your issue there. The Field cast to int? will not work unless your DataTable field matches the int? type.
Problem solved, I am working against a legacy access database and the data type was stored as Integer instead on Long Integer meaning it is represented as an Int16 in the data set hence the Invalid cast exception...

how to convert int to string in Linq to entities

My Db column in a string (varchar) and i need to assign it to a int value.
I am using linq to query.Though the code compiles am getting an error at the run time .
Thanks in advance.
PFB my query :
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
//(Int32)plan.cap_group_code,
Value = plan.cap_group_name
};
return vlauesCap.ToList();
The EF provider does not know how to translate Convert.ToInt() into SQL it can run against the database. Instead of doing the conversion on the server, you can pull the results back and do the conversion using linq to objects:
// the ToList() here causes the query to be executed on the server and
// the results are returned in a list of anonymous objects
var results = (from plan in entities.PA_RTM_CAP_Group
select new
{
Code = plan.cap_group_code,
Name = plan.cap_group_name
}).ToList();
// the conversion can now be done here using Linq to Objects
var vlauesCap = from r in results
select new Business.PartnerProfile.LookUp
{
Id = Convert.ToInt32(r.Code),
Value = r.Name
};
return vlauesCap.ToList();
You can't do this directly, what you can do is declare a private variable to handle your "mapped" value, and expose the unmapped property...
[Column(Name = "cap_group_code", Storage = "m_cap_group_code")]
private string m_cap_group_code;
public int cap_group_code {
get
{
return Int32.Parse(m_cap_group_code);
}
set
{
m_cap_group_code = value.ToString();
}
}
Try this:
var vlauesCap = from plan in entities.PA_RTM_CAP_Group
select new Business.PartnerProfile.LookUp
{
Id =Convert.ToInt32(plan.cap_group_code),
Convert.ToInt32(plan.cap_group_code),
Value = plan.cap_group_name
};
return vlauesCap.ToList();
Why aren't you using casting for such a purpose, which is a more effective way of achieving this.
Just replace Convert.ToInt32(plan.cap_group_code) with (int)plan.cap_group_code
Do remember, there should be a value in the string and is int, else it will show Exception. If you are not sure about it, then you can further expand the casting to use null coalesciting operator

Categories