What's the difference between List and HashSet in a class constructor with EF6?

c# entity-framework entity-framework-6

Question

I am using Entity Framework 6 and defining a table called ObjectiveDetail.

I've seen two ways to create the ObjectiveDetail class. One that creates a List and the other HashSet.

What's the difference?

public partial class ObjectiveDetail {
    public ObjectiveDetail() {
        this.SubTopics = new List<SubTopic>();
    }
    public int ObjectiveDetailId { get; set; }
    public int Number { get; set; }
    public string Text { get; set; }
    public virtual ICollection<SubTopic> SubTopics { get; set; }
}

public class ObjectiveDetail 
{
    public ObjectiveDetail() {
        this.SubTopics = new HashSet<SubTopic>();
    }
    public int ObjectiveDetailId { get; set; }
    public int Number { get; set; }
    public string Text { get; set; }
    public virtual ICollection<SubTopic> SubTopics { get; set; }
}
1
1
1/28/2014 12:12:51 PM

Accepted Answer

To expand on why its important that HashSet enforces uniqueness in this situation, the relationships that the navigation property represents must be thought of in terms of data modeling.

While you may have entity A related to entity B more than one time, even if both relationships are 1 -> many, each relationship on the A side is related to a given instance of the entity on the B side only once. Therefore, this is best represented with a HashSet.

In the case of the example above, A would have two HashSet navigation properties, B1 and B2, rather than one List to handle both relations.

0
1/28/2014 12:46:49 PM

Popular Answer

I think it depends if items on the collection should be unique or not, in terms of Database it's probably a unique constraint applied to a column.

Hashset contains only unique items, while List can contain duplicates.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow