ASP.NET Entity Framework 6 HashSet 或 List 的集合?

ASP.NET Entity Framework 6 HashSet or List for a collection?(ASP.NET Entity Framework 6 HashSet 或 List 的集合?)

本文介绍了ASP.NET Entity Framework 6 HashSet 或 List 的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 EF 模型如下所示:

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; }
}

这是此对象的 DDL:

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)
);

谁能告诉我应该使用哪个,甚至有区别,我什么时候使用 List 以及 HashSet (如果适用).

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.

谢谢

推荐答案

这取决于您的用例,但在大多数情况下,您只能将项目添加到集合中一次,因为例如每个状态仅应用于内容一次.我怀疑你可以让一个内容在一个状态中出现两次.因此 HashSet 是正确的数据结构,因为它可以防止重复.如果一个项目可以重复,List 是正确的,但我在实践中没有遇到这种情况,甚至不知道 EF 会如何处理它.

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.

作为旁注,我建议您不要在实体中包含项目集合,除非您需要它.例如,如果您正在构建一个 Web 应用程序来列出产品,您可能有一个视图,您可以在其中显示单个产品及其标签.因此,产品应该有一个标签的集合,以使这种情况变得容易.但是,您可能没有显示标签及其产品集合的页面,因此标签不应具有 Products 属性.它只是不关心相关产品.看来这个 Status 实体并不关心它的 Contents 集合.

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.

这篇关于ASP.NET Entity Framework 6 HashSet 或 List 的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:ASP.NET Entity Framework 6 HashSet 或 List 的集合?

基础教程推荐