ASP.NET Entity Framework 6 HashSet or list for collection?

My EF models are 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; } } 

However, I also saw implementations similar to:

 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 someone tell me what I should use or even there is a difference, and when I will use List and when HashSet, if applicable.

thanks

+8
c # sql-server entity-framework entity-framework-6
source share
2 answers

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 the content. I doubt that one content can be displayed twice in status. Therefore, HashSet is the correct data structure, as it will prevent duplication. In the case where one element can be duplicated, the List will be correct, but I have not come across this in practice and do not even know how EF will handle it.

As an additional note, I would advise you not to include a collection of elements in your entities if you do not need it. For example, if you are creating a web application for viewing products, you probably have a view where you display one product along with its tags. Therefore, a product must have a set of tags to make this case easy. However, you probably do not have a page that displays the tag with its product collection, and therefore the tag should not have the Products property. It just doesn't apply to related products. This Status object does not seem to care about its collection of contents.

+5
source share

So, HashSet<T> - definition

And List<T> does not have these features.

So, I think it's up to the desired features and performance (which is not significant on small sets). They can both be listed.

Performance (although there are probably tiny differences) will be evident in two parts: reading and writing. As Sean commented, there will be likely penalties for entries due to hash code calculations and unique comparisons. But reading is very fast ( o(1) ).

So, it all depends on the desired characteristics.

In my projects, I would use List<T> , but this is my convention. You can define your own agreement if you stick to it.

0
source share

All Articles