【问题标题】:Concrete type to choose for collection navigation properties of an EF6 entity type为 EF6 实体类型的集合导航属性选择的具体类型
【发布时间】:2022-12-23 19:00:19
【问题描述】:

下面是 Visual Studio 的“Code First from database”向导生成的代码块:

public partial class Doc {
  public Doc() {
    Attachments = new HashSet<UploadedFile>();
  }

  public virtual ICollection<UploadedFile> Attachments { get; private set; }
  // UploadedFile is a table with one of its foreign key column pointing to Doc's primary key column
}

正如所见,Visual Studio 在构造函数中将 Attachments 初始化为 HashSet。但我希望该集合保留插入顺序。

如果我将具体类型从 HashSet 更改为 List 是否安全?

此外,如果我想仍然保持“集合”性质(不重复插入)并同时保留插入顺序,我有什么选择?

【问题讨论】:

    标签: .net collections set entity-framework-6


    【解决方案1】:

    集合导航属性表示通过外键关系从另一个表返回的记录。理论上数据库服务器在返回记录时不保证任何顺序(除非使用 ORDER BY),因此集合导航属性的接口是ICollection&lt;&gt;而不是IList&lt;&gt;。因此,试图在收集容器上保持内在的秩序是一个错误的方向。

    相反,订单信息应该与集合中的对象有关。问题中的 UploadedFile 类型应该有一个存储订单值的属性(当然,数据库表应该有相应的列)。这样,如果需要以特定顺序访问Doc.Attachments,则可以使用OrderBy。这是最自然的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多