Return a List<> from method

时间:2018-12-03 13:24:22

标签: c# .net linq

I am wanting to return a List<string> from my ASP.NET API Call. I am getting the compile error below - but am unsure on how to resolve it.

Cannot implicitly convert type System.Linq.IQueryable<<anonymous type: string compname, int invoicenum, decimal? invoiceamt, System.DateTime? invoicedate, System.DateTime? invoicepaddate>> to System.Collections.Generic.List<ITD>. An explicit conversion exists (are you missing a cast?)

And this is my syntax:

public IEnumerable<ITD> Get()
{
    List<ITD> result = new List<ITD>();
    XE entities = new XE();
    result = (from a in entities.Companies
              join b in entities.Invoices
              on a.compNumber equals b.compNumber
              select new
              {
                  compname = a.Company1,
                  invoicenum = b.InvoiceNum,
                  invoiceamt = b.InvoiceAmt,
                  invoicedate = b.InvoiceDueDate,
                  invoicepaddate = b.InvoicePaidDate
              });
    return result;
}

2 个答案:

答案 0 :(得分:1)

您返回的是anonymous typeIQueryable,而不是IEnumerable<ITD>。将您的代码更改为此:

select new ITD

如果仍然出现错误,可能是因为无法投影到映射的实体,则需要使用ITD实体创建具有所需属性的DTO类,如下所示:

public class ITDDTO
{
    public string Company { get; set; }
    //And other properties
}

也不要忘记在查询的末尾添加.ToList()

答案 1 :(得分:-2)

您的LINQ查询返回IQueryable接口的实例,但是您的变量resultList<ITD>,请尝试执行以下操作:

List<ITD> result = new List<ITD>(/*Insert LINQ here*/)
相关问题