将Linq数据查询转换为对象类型

3

我遇到了错误

"无法将类型为'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个回答

9

您的查询返回一个 IEnumerable<Client>,您需要使用 FirstOrDefaultFirst 或者 SingleOrDefault。请参考 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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接