Ovidiu Ovidiu - 3 months ago 9
C# Question

How to write one to many classes c#

Here is my problem: I need to represent a one to many relationship. One Company has many Stores.
This is my code:

public class Company
{
public int Id;

public string Name;

public string Email;

public Guid GUID;
}

public class Store
{

public int Id;

public int CompanyId;

public string Name;

public int NoOfEmployees;

public Guid GUID;
}


My question is: how this works without using virtual and hashsets? is this implementation ok?

Thank you.

Answer

You could use simply a List where you would save all the Stores that one company has.

public class Company 
{
    public int Id;

    public string Name;

    public string Email;

    public Guid GUID;
    // List of all Stores
    public List<Store> AllTheStores;

    public Company()
    {
        AllTheStores = new List<Store>();
    }
}

EDIT:

The property: public int CompanyId; makes only really sense if more than one Company can have the same Store. Otherwise you could access the stores via the Company:

Company c = new Company();

Store s = c.AllTheStores.Find(x=>x.Name == "MyStore");

// or 
List<Store> largeStores = c.AllTheStores.Where(x=>x.NoOfEmployees > 200).ToList();