Below is a code block generated by Visual Studio's "Code First from database" wizard:
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
}
As seen Visual Studio initialize Attachments
as a HashSet in constructor. But I want that collection to preserve insertion order.
Is it safe if I change the concrete type from HashSet to List?
Moreover, if I want to still keep the "set" nature (no duplicate insertion) and preserve insertion order at the same time, what choice do I have?
Collection navigation properties represent records returned from another table by foreign key relations. Theoretically database servers don't guarantee any order when returning records (unless ORDER BY is used), hence the interface of collection navigation properties is ICollection<>
but not IList<>
. Therefore, trying to maintain an intrinsic order on the collection container is a wrong direction.
Instead, the order information should pertain to the objects in the collection. The UploadedFile
type in the question should have a property storing the order value (and the database table should have the corresponding column, of course). With that, OrderBy
can be used if one needs to access Doc
.Attachments
in that particular order. This is the most natural way.