Search code examples
entity-frameworkasp.net-mvc-4hashseticollection

structure of the classes having foreign key relationship generated from entity framework


I generated my classes from the database via Entity Framework. The classes name are the tables name and the properties are the fields. Now I've three tables , App_users, Book, Course.

App_users has one to many relationship with book and course (userid is foreign key). When I see the user class, it has the structure like this:

public partial class App_users
{
    public App_users()
    {
        this.Book = new HashSet<Book>();
        this.Course = new HashSet<Course>();
    }

    public int USERID { get; set; }
    public string USERNAME { get; set; }
    public virtual ICollection<Book> Book { get; set; }
    public virtual ICollection<Course> Course { get; set; }
}
  1. I want to know that why these tables (Book & Course) are defined as HASHSET inside the constructor. What is the use/importance of doing so?
  2. Again the classes Book & Course are defined as ICOLLECTION. What is the use/importance of doing this?

I know that this structure is used for showing the foreign key relationship in a table.

Please can anyone explain me this.


Solution

  • First Question:

    The HashSet is mostly useful in situations where insertion and removal times are very important, such as when processing data. It is also extremely useful for comparing sets of data (again when processing) using operations like intersect, except, and union. In any other situation, the cons generally outweigh the pros. (https://stackoverflow.com/a/18158905/1845408)

    Second question:

    ICollection<> (MSDN: http://msdn.microsoft.com/en-us/library/92t2ye13.aspx) for a list of objects that needs to be iterated through and modified, List<> for a list of objects that needs to be iterated through, modified, sorted, etc (See here for a full list: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx). https://stackoverflow.com/a/10113331/1845408