Linq To Sql问题

时间:2011-09-10 17:31:25

标签: linq-to-sql

它会给我错误无法转换类型的对象。

  public class CusInfomration
   {
      public string CustomerName { get; set; }
      public string CustomerID { get; set; }
      public string OrderDate { get; set; }
      public string OrderId { get; set; }
   }

  var CustomerFromWash =  from p in _NorthWindDataContext.Customers
                          join q in _NorthWindDataContext.Orders 
                          on p.CustomerID   equals q.CustomerID
                          where p.Region == "WA"
                          select new
                         {                                                   
                             CustomerName =Convert.ToString(p.CompanyName),
                             CustomerID = Convert.ToString(p.CustomerID),
                             OrderId = Convert.ToString(q.OrderID),
                             OrderDate = Convert.ToString(q.OrderDate),
                          };

  List<cusinfomration> lstCust = (List<cusinfomration>)CustomerFromWash;

1 个答案:

答案 0 :(得分:4)

该LINQ查询返回IQueryable<T>IQueryable<T>是一个接口而List<T>没有实现它,所以底层的具体实现无法是List<T>(它确实实现了IEnumerable<T>,所以a施放到那将是有效的)。即使它不是一个安全的演员,因为.NET人们可能希望有一天改变底层实现,你的演员阵容将被打破。即使它最初起作用也不是一个好主意。

您可以在LINQ查询的返回值上调用ToList()

var CustomerFromWash = (from p in _NorthWindDataContext.Customers
                        join q in _NorthWindDataContext.Orders 
                        on p.CustomerID   equals q.CustomerID
                        where p.Region == "WA"
                        select new
                        {                                                   
                           CustomerName =Convert.ToString(p.CompanyName),
                           CustomerID = Convert.ToString(p.CustomerID),
                           OrderId = Convert.ToString(q.OrderID),
                           OrderDate = Convert.ToString(q.OrderDate),
                        }).ToList();

即便如此,您仍然选择匿名类型的集合,而不是CustInformation个对象。如果您想要返回CustInformation个对象,则需要:

select new CustInformation 
{
    // set properties here
}