无法转换AnonymousType#1 ti IEnumerable

时间:2017-04-19 14:30:12

标签: c# linq ienumerable anonymous-types

我在.cs页面中声明了一个模型

public class InstrumentDetails
{
    public long PullNo { get; set; }
    public string Description { get; set; }
    public int New { get; set; }
    public int LN { get; set; }
    public int PR { get; set; }
    public int Any { get; set; }
}

之后我会以这种方式检索数据:

IEnumerable<InstrumentDetails> instrumentdetails = (from p in NemcDb.tblPulls
    join
    pi in NemcDb.tblPullInstruments
    on
    p.PullId equals pi.PullId
    join
    i in NemcDb.tblInstruments
    on
    pi.InstrumentCode equals i.InstrumentCode
    select new
    {
        PullNo = p.PullNo.Value,
        InstrumentType = i.Description,
        New = pi.NewQuantity,
        LN = pi.LNQuantity,
        PR = pi.UsedQuantity,
        Any = pi.AnyQuantity
    }).Where(i => i.PullNo.ToString() == item);

但它给了我错误

  

无法转换System.Linq.IQueryable&lt; AnonymousType#1&gt;&#39;到&#39; System.Collections.Generic.IEnumerable&lt;&gt;&#39;。存在显式转换(您是否错过了演员?)

我哪里错了?......我无法通过......请帮助。

2 个答案:

答案 0 :(得分:2)

您不会告诉您需要类型为InstrumentDetails的对象,而是创建一个匿名类型。将select new { ...更改为select new InstrumentDetails { ...,然后再调用ToList()ToEnumerable()ToArray(),以便实际运行查询。

答案 1 :(得分:0)

答案是:

            IEnumerable<InstrumentDetails> instrumentdetails = (from p in NemcDb.tblPulls
                                                            join
                                                            pi in NemcDb.tblPullInstruments
                                                            on
                                                            p.PullId equals pi.PullId
                                                            join
                                                            i in NemcDb.tblInstruments
                                                            on
                                                            pi.InstrumentCode equals i.InstrumentCode
                                                            select new InstrumentDetails
                                                            {
                                                                PullNo = p.PullNo.Value,
                                                                InstrumentType = i.Description,
                                                                New = pi.NewQuantity,
                                                                LN = pi.LNQuantity,
                                                                PR = pi.UsedQuantity,
                                                                Any = pi.AnyQuantity

                                                            }).Where(i => i.PullNo.ToString() == item).ToList();

    }

我多么愚蠢............