Search code examples
visual-studio-2010silverlightlinqentity-framework-4wcf-ria-services

Return the result of joining two tables in Silverlight 4.0


Main Code:

    DomainServiceAccountManager d = new DomainServiceAccountManager();
    EntityQuery<ListBuy> q = d.GetListMemberBuyQuery();
    LoadOperation<ListBuy> l = d.Load(q);
    DGListBuy.ItemsSource = l.Entities;

The code:

public IQueryable<ListBuy> GetListMemberBuy()
{
    var membuy =
    from mem in this.ObjectContext.Members
    from b in this.ObjectContext.Buys.Where(b => b.ID_member == mem.ID)
    .OrderByDescending(b => b.ID)
    .DefaultIfEmpty()
    select new { b.ID, mem.Name, b.Money, b.Tarikh };
    return membuy;
}

I get the following message:

Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.IQueryable<AccountManager.Web.ListBuy>'. An explicit conversion exists (are you missing a cast?)


Solution

  • You method GetListMemberBuy actually returns an IQueryable of anonymous type instead of an IQueryable of type ListBuy. These are not identical, hence the (compile time?) error.

    I can only assume that ListBuy also exists in the database, but if so, then you can remove the anonymous type.

    public IQueryable<ListBuy> GetListMemberBuy()
    {
        var membuy =
        from mem in this.ObjectContext.Members
        from b in this.ObjectContext.Buys.Where(b => b.ID_member == mem.ID)
        .OrderByDescending(b => b.ID)
        .DefaultIfEmpty()
        select new ListBuy() { ID = b.ID, Name = mem.Name, Money = b.Money, Tarikh = b.Tarikh }; // <-- new ListBuy() !!
        return membuy;
    }
    

    If ListBuy does not exist in the database, then you cannot return an IQueryable. Maybe this will work.

    public IEnumerable<ListBuy> GetListMemberBuy()
    {
        var membuy =
        from mem in this.ObjectContext.Members
        from b in this.ObjectContext.Buys.Where(b => b.ID_member == mem.ID)
        .OrderByDescending(b => b.ID)
        .DefaultIfEmpty()
        select new { b.ID, mem.Name, b.Money, b.Tarikh };
        return membuy
            .AsEnumerable()
            .Select(b => new ListBuy() { 
                ID = b.ID, Name = b.Name, Money = b.Money, Tarikh = b.Tarikh
            });
    }
    

    All this is a bit speculation since you didn't include the ListBuy class definition in your question.