8

What is the best practice to define a One-to-Many relationship in EF Core?

Is it recommended to generally use lists, as these offer more functionalities? Then rather the interface IList instead of List, as it does not define the implementation? If it does matter, on what criteria should I pick one or the other?

Microsoft suggests the following https://learn.microsoft.com/en-us/ef/core/modeling/relationships

public class Blog
{
    public int BlogId { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

Whereas

http://www.entityframeworktutorial.net/efcore/configure-one-to-many-relationship-using-fluent-api-in-ef-core.aspx

https://www.learnentityframeworkcore.com/configuration/one-to-many-relationship-configuration suggest ICollections

Is the following answer of 2011 still valid in EF Core?

https://stackoverflow.com/a/7655974/10148774

raw
  • 99
  • 1
  • 5

1 Answers1

13

Your decision should depend on the operations that your use case will need.

In general, you have three main options:

  • IEnumerable<> for a list of objects that only needs to be iterated through (no additional operations such as modifications).
  • ICollection<> for a list of objects that needs to be iterated through and modified.
  • IList<> for a list of objects that needs to be iterated through, modified, sorted, access by index...

Now this may lead you to the following question: "So I will always use List because it provides the most functionality". In this case you should keep in mind that this option has the most overhead and a good object-oriented practice is to program towards the interface and not the implementation. Implementations can and will change.

Long story short: There is no golden rule here, you need to analyze and make the proper trade-offs for your specific scenario in order to make the best choice.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
leandro.andrioli
  • 997
  • 5
  • 12
  • 5
    Ok thanks Leonardo. And then why not use interface Ilist<> instead of List<>? – raw Mar 11 '19 at 10:08