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
List is the concrete class. This class implements IList, ICollection, IEnumerable.
An IList extends ICollection. An IList can perform all operations combined from IEnumerable and ICollection, and some more operations like inserting or removing an element in the middle of a list.
The main difference between List and IList in C# is that List is a class that represents a list of objects which can be accessed by index while IList is an interface that represents a collection of objects which can be accessed by index.
An IEnumerable supports filtering elements using where clause. ICollection is another type of collection, which derives from IEnumerable and extends it's functionality to add, remove, update element in the list.
The decision you should choose will depend on which operations you need to execute.
In general, you have three main options:
Now you can think: So I will always use List because it provides the most functionality, but keep in mind that it 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.
Then you need to balance and analyze your specific scenario to make the best choice.
Regards,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With