Search code examples
c#linq

LINQ query fitting into a model


I have a model Version. This houses the information to contain one unique version of a document.

In my view model I set it up like so:

public virtual ICollection<IPACS_Version> rejectionList { get; set; }

So I can now have a collection of Version documents.

Here is the LINQ:

model.rejectionList = (from v in db.IPACS_Version
                        join d in db.IPACS_Document
                        on v.documentID equals d.documentID
                        where v.dateRejected != null && (d.createdBy == currUser || d.requester == currUser)
                        select v);

This is giving me the following error:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.ICollection'. An explicit conversion exists (are you missing a cast?)

The line can return to me 0 to many "versions". So what I think I am not understanding correctly is how come this LINQ query cannot fit into my Version model, since the query returns 0 to many versions?


Solution

  • LINQ query returns IQueryable<T>, while you demand it to be of type ICollection<T>. These two interfaces are very distinct and you need to bring them into one nature. To say technically, you need to materialize IQueryable<T> into some sort of in-memory sequence of data, which would allow add and removal of it's members (nature of ICollection interface abstraction)

    Quick solution is to add ToList in the end of the query

    model.rejectionList = (from v in db.IPACS_Version
                            join d in db.IPACS_Document
                            on v.documentID equals d.documentID
                            where v.dateRejected != null && (d.createdBy == currUser || d.requester == currUser)
                            select v).ToList();
    

    since IList implements ICollection<T>, this should work fine.