gpt4 book ai didi

asp.net - 将 Linq 数据查询转换为对象类型

转载 作者:行者123 更新时间:2023-12-02 10:26:10 25 4
gpt4 key购买 nike

我收到错误

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

最佳答案

您的查询返回 IEnumerable<Client> ,您需要 FirstOrDefault , First , 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()

关于asp.net - 将 Linq 数据查询转换为对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16272585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com