James Wilson
James Wilson

Reputation: 5150

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?

Upvotes: 2

Views: 68

Answers (3)

Justin Niessner
Justin Niessner

Reputation: 245449

If you can't change your view model to use IEnumerable<T> rather than ICollection<T>, then the easiest way to solve your issue is to call ToList on the final query. List<T> implements ICollection<T>.

Upvotes: 1

Ilya Ivanov
Ilya Ivanov

Reputation: 23636

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.

Upvotes: 3

Habib
Habib

Reputation: 223282

Define your property as IEnumerable<T>

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

Upvotes: 1

Related Questions