将Linq Data查询转换为对象类型

时间:2013-04-29 06:37:25

标签: asp.net asp.net-mvc linq

我收到了错误

  

“无法转换类型的对象   输入'System.Data.Linq.DataQuery`1 [StockManagement.Models.Client]'   'StockManagement.Models.Client'。“

public class Client
        {
            public int ClientID { get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
            public string Mobile { get; set; }
            public string Telephone { get; set; }
            public string Fax { get; set; }
            public string Company { get; set; }
        }


private StockDataClassesDataContext dc;
 public Client GetClient(int clientID)
        {
            dc = new StockDataClassesDataContext(ConString.DBConnection);
            Client query = (Client)(from tbclient in dc.tblClients
                                  where tbclient.ClientID == clientID
                                  select new Client
                                  {
                                      Address = tbclient.Address,
                                      ClientID = tbclient.ClientID,
                                      Company = tbclient.Company,
                                      Fax = tbclient.Fax,
                                      Mobile = tbclient.Mobile,
                                      Name = tbclient.Name,
                                      Telephone = tbclient.Telephone
                                  });
            return query;
        }

1 个答案:

答案 0 :(得分:9)

您的查询返回IEnumerable<Client>,您需要FirstOrDefaultFirstSingleOrDefault ..请查看最适合您的MSDN。

Client query = (from tbclient in dc.tblClients
                                  where tbclient.ClientID == clientID
                                  select new Client
                                  {
                                      Address = tbclient.Address,
                                      ClientID = tbclient.ClientID,
                                      Company = tbclient.Company,
                                      Fax = tbclient.Fax,
                                      Mobile = tbclient.Mobile,
                                      Name = tbclient.Name,
                                      Telephone = tbclient.Telephone
                                  }).FirstOrDefault()