0

I was learning relationships in model classes. Please see the attached image for the table relationships. There are three tables, department, employee, location. When model classes are created for these tables, I am confused regarding navigational property. employee class:

public class employee
{
    public employee()
    {
        this.location = new HashSet<location>();
    }
    //attributes
    
    public virutal department department {get;set}
    public virtual ICollection<location> locations {get;set}
}

then in department class:

public class department
{
    //attributes
    public virutal ICollection<employee> employees {get;set}
}

in location class:

public class location
{
    public virutal employee employee {get;set}
}

Why in employee class department is defined like virutal department department but location is defined as virtual ICollection<location> locations. Why using ICollection only with locataion?

And in department model, employee class is defined as virutal ICollection<employee> employees but in location model employee is defined as virutal employee employee. Why is it so, please clarify.

Also in employee class location is defined as HashSet<location>() in constructor, and why is it defined like this ? This navigational property is making me confused to proceed further in the project. Please make me clarify regarding this. Thank You!!!

enter image description here

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
nischalinn
  • 1,133
  • 2
  • 12
  • 38

1 Answers1

0

According to this logic you shared it says

An Employee can be attached to one Department but multiple locations. This is called one to many relation

A Department can have multiple Employees A Location can have one Employee. so that means An employee can work at more than 1 locations but Location can only have one Employee This is one to many too.

HashSet is a key-value pair data type in C#. It is similar to objects in JavaScript;

ICollection is a generic interface. It takes a type and can hold multiple values inside just like List type. But it doesnt have methods like Add, Clear or Contains. In order to have those methods you should implement IList interface.

Constructor of employee initializes a hashset of locations everytime it initializes. Meaning you initialize a hashset of locations attached to it. (meaning on every instance, simply calling the class object)

and that virtual keyword in front of your properties causes a thing 'lazy loading'

lazy loading ef

forth
  • 55
  • 1
  • 9