使用LINQ基于另一列的值选择列

时间:2011-12-07 19:23:51

标签: c# linq entity-framework linq-to-entities anonymous-types

我的问题类似于这里的问题:Select a specific column based on another column's value但在LINQ中,使用VS2010,C#,。NET 4.0和LINQ to Entities

以下是我遇到问题的片段:

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);
             }

ExecuteDataSet命令抛出InvalidCastException并显示消息:

  

无法将参数值从&lt;&gt; f__AnonymousType0`1转换为字符串。

有什么问题,为什么这个匿名类型在尝试将其解释为字符串时会抛出错误?

1 个答案:

答案 0 :(得分:2)

替换

MyDatabase.AddInParameter(sqlcmd, "@BillingNumber", DbType.String, billingnumber);

MyDatabase.AddInParameter(sqlcmd, "@BillingNumber", DbType.String, billingnumber.BillingNumber);

var billingnumber是一个匿名类型,其中包含一个字符串属性BillingNumber。您需要引用该属性,它不能自动转换为其第一个成员。

另一种方法是替换

select  new
{   BillingNumber = (
    o.SiteID == "NYC"? o.NYCBillingNumber.Trim():
    o.SiteID == "DAL" ? o.DallasBillingNumber.Trim(): "unknown") 
}

select (
    o.SiteID == "NYC"? o.NYCBillingNumber.Trim():
    o.SiteID == "DAL" ? o.DallasBillingNumber.Trim(): "unknown")

然后你根本不需要匿名类型。