如何将System.Data.Entity.Infrastructure.DbQuery类型转换为System.Collections.Generic.List类型?

时间:2016-06-02 14:55:09

标签: c# linq

我有两个简单的列表:

public partial class Visitor
{
    public Visitor()
    {
        this.Visits = new HashSet<Visit>();
    }

    public int Id { get; set; }
    public int PermitId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public bool IsValid { get; set; }
    public System.DateTime RegistrationDate { get; set; }
    public byte[] Picture { get; set; }
    public virtual ICollection<Visit> Visits { get; set; }
}

public partial class Visit
{
    public int Id { get; set; }
    public int VisitType { get; set; }
    public System.DateTime VisitDate { get; set; }
    public Nullable<int> Visitor_Id { get; set; }

    public virtual Visitor Visitor { get; set; }
}

在WCF方法中,我编写了查询并尝试返回结果:

public List<Visitor> AllVisitors()
        {
            using (var te = new TurnstileDbEntities())
            {
                te.Configuration.ProxyCreationEnabled = false;


                return (List<Visitor>) te.Visitors.SelectMany(visitors => te.Visits
                    .Where(o => o.Visitor_Id == visitors.Id)
                    .DefaultIfEmpty(), (visitors, visit) => new {visitors, visit});
            }
        }

好吧,正如预期的那样,我收到了一个例外:

  

其他信息:无法转换对象类型   “System.Data.Entity.Infrastructure.DbQuery 1[<>f__AnonymousType0 2 [TurnstileWcfService.Visitor,TurnstileWcfService.Visit]]”   输入   “System.Collections.Generic.List`1 [TurnstileWcfService.Visitor]”。

确定。我改写了这个。 宣布新课程。

public class JoinResult
{
    public Visitor Visitors { get; set; }
    public Visit Visits { get; set; }
}

并重写方法。

   public IQueryable AllVisitors()
    {
        using (var te = new TurnstileDbEntities())
        {
            te.Configuration.ProxyCreationEnabled = false;

            return te.Visitors.Join(te.Visits, 
                r => r.Id, a => a.Visitor_Id, (r, a) => new JoinResult
            {
                Visits = a,
                Visitors = r
            });
        }
    }

它是有效但我想使用访客类。访问者类包含ICollectionVisits,我想填充它。如果没有声明新类,我如何在Linq语句中执行此操作?

此外,我可以通过以下代码获得我想要的内容。但我不喜欢这个。

var visitors = te.Visitors.ToList();
foreach (var item in visitors)
{
      item.Visits = te.Visits.Where(v => v.Visitor_Id == item.Id).ToList();
}

1 个答案:

答案 0 :(得分:6)

Gert Arnold是对的,试试:

List<Visitor> visitors = te.Visitors.Include(v => v.Visits).ToList();

编辑我也按照以下方式工作:

List<Visitor> visitors = te.Visitors.Include("Visits").ToList();