Convert IQueryable to Custom Class

点点圈 提交于 2019-12-23 18:54:23

问题


I have a LINQ query as below,

public AddXferData DisplayXferDataToBeModified(int ID)
    {
        try
        {
            var resultSet = (from items in DataContext.Transfers
                             where items.Transfer_ID.Equals(ID)
                             select new AddXferData
                             {
                                 XferID = items.Transfer_ID,
                                 LogicalName = items.Logical_Name,
                                 RoutCode = items.Route_Code,
                                 Label = items.Label,
                                 OnNetDNA = items.On_Net_DNA,
                                 OnNetDNB = items.On_Net_DNB,
                                 FailMessage = items.Failure_Message,
                             });
            return resultSet;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

But my resultSet asks for a Cast and the message I get is

"Cannot implicitly convert type 'System.Linq.IQueryable' to 'ICMAdministration.Data.AddXferData'. An explicit conversion exists (are you missing a cast?)

I need to cast the resultset to type AddXferData. Can you let me know how this can be achieved. Your help in this regard is very much appreciated.

Regards, Raghu


回答1:


If it's a single AddXferData, then try:

return resultSet.First();

or

return resultSet.FirstOrDefault();

If it can return null (as in ID not found or something)




回答2:


return resultSet.SingleOrDefault();



回答3:


your query will return the collection of AddXferData objects. if you dont expect single result , change the function signature.

 public list<AddXferData> DisplayXferDataToBeModified(int ID) 

and return the list resultSet.ToList();



来源:https://stackoverflow.com/questions/10344915/convert-iqueryable-to-custom-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!