Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Linq Data query to object type

I'm getting the error

"Unable to cast object of type 'System.Data.Linq.DataQuery`1[StockManagement.Models.Client]' to type '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;
        }
like image 385
chamara Avatar asked Nov 24 '25 03:11

chamara


1 Answers

Your query returns an IEnumerable<Client>, you need either FirstOrDefault, First, SingleOrDefault.. look at MSDN for the one that best suits you.

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()
like image 148
Lews Therin Avatar answered Nov 25 '25 17:11

Lews Therin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!