Entity Framework – Why not to use IEnumerable on many-many/one-many relationships?

When using a Code First database approach with Entity Framework, you will often have nested types in your models which refer to other models giving us a ‘has-a’ relationship or as it’s commonly known as, aggregation. When getting grips with Entity, you may find yourself representing aggregation over a collection by using the most popular interface which enumerates over a collection, IEnumerable<T>. As the name suggests, IEnumerable<T> will only allow you to enumerate over a collection and therefore does not contain any of the usual CRUD operations like Add(), Update(), Remove() etc… This makes it impossible for you to change this collection property within your model and in-effect gives you an entry to an immutable collection.

Example model using IEnumerable<T>:

public class Person
{
  [Key] public int Id { get; set; }
  public string Name { get; set; }
  public IEnumerable<Thing> FavouriteThings { get; set; } //Can only be enumerated - Will not write new values to database
}

public class Thing
{
  [Key]public int Id { get; set; }
  public string Name { get; set; }
}

The best option is to work with Types which implement ICollection<T> (they will also inherently implement IEnumerable<T>). This will ensure that your concrete types will be guaranteed to have the basic CRUD operations so you can work with your data along with adding dummy data using the Seed() method.

public class Person
{
  [Key] public int Id { get; set; }
  public string Name { get; set; }
  public ICollection<Thing> FavouriteThings { get; set; } //CRUD operations supported - See: https://msdn.microsoft.com/en-us/library/92t2ye13(v=vs.110).aspx
}

Leave a Reply