ASP.NET Entity Framework 6 HashSet or List for a collection?

asp.net c# entity-framework entity-framework-6 sql-server

Question

My EF models appear as follows:

public class ContentStatus
{
    public ContentStatus()
    {
        this.Contents = new List<Content>();
    }

    public int ContentStatusId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Content> Contents { get; set; }
}

But I've also seen implementations that resemble this:

public class ContentStatus
{
    public ContentStatus()
    {
        this.Contents = new HashSet<Content>();
    }

    public int ContentStatusId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Content> Contents { get; set; }
}

This object's DDL is available here:

CREATE TABLE [dbo].[ContentStatus] (
    [ContentStatusId] INT           NOT NULL,
    [Name]            NVARCHAR (50) NOT NULL,
    CONSTRAINT [PK_ContentStatus] PRIMARY KEY CLUSTERED ([ContentStatusId] ASC)
);

Could someone please tell me which to use, if there is a difference, and when to use the List and when to use the HashSet, if applicable.

Thanks

1
12
2/23/2015 10:54:04 AM

Popular Answer

Depending on your use case, you can usually only add an item to the collection once because, for instance, each status is only ever assigned to a piece of content once. Doubtfully, a status can include the same content twice. HashSet is the ideal data structure since it avoids duplication. List might be OK if one item could be duplicated, but I haven't seen this in practice and don't even know how EF would handle it.

A collection of items should not be included in your entities unless you really need to. For instance, if you are developing a web application to list products, your view will likely show a single product together with its tags. To make this scenario simple, Product should have a collection of Tags. The Tag shouldn't have a Products attribute because you most likely do not have a page that shows a Tag and its collection of products. It simply doesn't give a damn about associated goods. It appears that this Status object doesn't give a damn about the contents of its collection.

6
2/23/2015 11:00:34 AM


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