My question is similar to the one here: Select a specific column based on another column's value but in LINQ, using VS2010, C#, .Net 4.0 and LINQ to Entities
Here’s the snippet I’m having an issue with:
var BillingNumbers = (from o in mycontext.MyOrders
where o.Status.Description.Trim().ToUpper().Equals("SHIPPED")
&& (o.ActualShipDate >= date1.Date && o.ActualShipDate < date2.Date)
select new
{BillingNumber = (
o.SiteID == "NYC"? o.NYCBillingNumber.Trim():
o.SiteID == "DAL" ? o.DallasBillingNumber.Trim(): "unknown")
});
foreach (var billingnumber in BillingNumbers)
{
sqlcmd = MyDatabase.GetStoredProcCommand("MyBillingNumberSP") as SqlCommand;
sqlcmd.CommandTimeout = Int32.Parse(Settings.Default.SQL_COMMAND_TIMEOUT.ToString());
MyDatabase.AddInParameter(sqlcmd, "@BillingNumber", DbType.String, billingnumber);
MyDatabase.AddOutParameter(sqlcmd, "@MyOutputParam", DbType.Boolean, 1);
LobjDS = MyDatabase.ExecuteDataSet(sqlcmd); //GETTING AN ERROR HERE
bool JobbingApplied = Convert.ToBoolean(MyDatabase.GetParameterValue(sqlcmd, "@MyOutputParam"));
Console.WriteLine(billingnumber);
}
The ExecuteDataSet command throws an InvalidCastException with the message:
Failed to convert parameter value from a <>f__AnonymousType0`1 to a String.
What is wrong and why is this anonymous type throwing an error when attempted to interpret it as string?
Replace
with
var billingnumberis a anonymous type with one string propertyBillingNumber. You need to reference that property, it is not automatically convertible to its first member.An alternative is to replace
with
Then you don’t need the anonymous type at all.