I have two simple Lists:
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; }
}
In WCF method i wrote query and tried to return result:
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});
}
}
Well, as expected, I received an exception:
Additional information: Failed to cast the type of object "System.Data.Entity.Infrastructure.DbQuery
1[<>f__AnonymousType0
2[TurnstileWcfService.Visitor,TurnstileWcfService.Visit]]" to type "System.Collections.Generic.List`1[TurnstileWcfService.Visitor]".
Ok. I rewrite this. Declare new class.
public class JoinResult
{
public Visitor Visitors { get; set; }
public Visit Visits { get; set; }
}
And rewrite method.
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
});
}
}
It is works but i want use Visitor class. Visitor class contain ICollectionVisits and i want populate it. How can I do this in Linq statement without declaration of new class?
Also I can get what i want in following code. But I don't like this.
var visitors = te.Visitors.ToList();
foreach (var item in visitors)
{
item.Visits = te.Visits.Where(v => v.Visitor_Id == item.Id).ToList();
}