1

I am using Entity Framework to select entries from a database

List<Entry> entries = dbContext.entries.ToList();

Codeanalysis tells me Warning CA1002: I found out that I should use Collection instead of List. But there is no .ToCollection() Method. Is this warning useless when using EF or what is the best practice there?

Update: When doing

Collection<Entry> entries = dbContext.entries.ToList();

It says something like

type List<Entry> can not be cast to Collection<Entry>

L3n95
  • 1,505
  • 3
  • 25
  • 49
  • Collection entries = dbContext.entries.ToList(); https://msdn.microsoft.com/library/ms182142.aspx – anmarti Mar 16 '17 at 08:54

3 Answers3

2

Not useless. What its saying is that rather than using generic list you could use one of the generic collections to store your results. I see that you are using EF, so most probably your dbContext.Entries is am IQueryable and when you use ToList() on it, it materializes the queryable and gives you the results.

So, to suppress the error you could use something like:

ICollection<Entry> collection = new List<Entry>();

or cast the results to a collection instead in a similar way

Jinish
  • 1,983
  • 1
  • 17
  • 22
  • Okay returning ICollection fixed this. Now I can't use the find()-Method instead I have to use a Linq-Query I think. – L3n95 Mar 16 '17 at 09:06
2

The codeanalysis point in question is not complaining about your use of ToList() in the method, but rather that you're returning a List<T> from your method

If you change your signature (for example) then it will be happy:

public ICollection<Entry> GetEntries()
{
    return dbSet.Entries.ToList();
}
Matthew Steeples
  • 7,858
  • 4
  • 34
  • 49
  • Okay returning ICollection fixed this. Now I can't use the find()-Method instead I have to use a Linq-Query I think. – L3n95 Mar 16 '17 at 09:06
  • Yes. It depends on how you want to use this elsewhere. Linq will work on collections, whereas Find will only work on List objects. Sometimes it makes sense to ignore code analysis recommendations depending on your particular use case – Matthew Steeples Mar 16 '17 at 09:36
  • @L3n95 - it might be worth having a look at https://stackoverflow.com/questions/271710/collectiont-versus-listt-what-should-you-use-on-your-interfaces – Matthew Steeples Mar 16 '17 at 13:11
1

Maybe write an extension method? Haven't tested this code but something like this:

public static Collection<T> ToCollection<T>
        (this IEnumerable<T> source)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            return new Collection<T>(source);
        }
Lysgaard
  • 234
  • 3
  • 11