My EF models look like this:
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; }
}
However I have also seen implementatins looking like 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; }
}
Here is the DDL for this Object:
CREATE TABLE [dbo].[ContentStatus] (
[ContentStatusId] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_ContentStatus] PRIMARY KEY CLUSTERED ([ContentStatusId] ASC)
);
Can anyone tell me which I should use or even is there a difference and when would I use the List and when the HashSet if that applies.
Thanks
It depends on your use case but in most cases you can add an item to the collection only once because for example each status is applied only once to a content. I doubt you can have one content appear twice in a status. Therefore HashSet is the correct data structure as it will prevent duplicates. In case where one item can be duplicated List would be correct but I have not encountered this in practice and do not even know how EF would handle it.
As a side note I would advise that you do not include a collection of items in your entities unless you need it. For example if you are building a web app to list products you probably have a view where you display a single product together with its tags. Therefore Product should have a collection of Tags to make this case easy. However you probably do not have a page that displays a Tag with its collection of products and therefore the Tag should not have a Products property. It just doesn't care about related products. It seems that this Status entity does not care about its collection of Contents.