In our previous two articles we explained how to implement a One-To-One and a One-To-Many relationship in a C# class. You can read them here:
One to one relationship in C# class
Implement one to many relationship in C# class.
In this article we will learn to implement a Many-To-One relationship in a C# class. As in the previous two articles, we will explain the scenario where a Many-To-One relationship is relevant. Think about the situation where we want to represent a relationship between a teacher and a student. It is a very common scenario where one student is guided by many teachers. Another relationship is between a customer and the shop. Many customers may come into a shop for shopping. So, in those situations we can build a Many-To-One relationship.
We can think of a Many-To-One relationship as just the opposite of a One-To-Many relationship. Let's see a few examples and a practical implementation.
Relation between customer and shopkeeper
Here we will implement a relationship between customer and shop. Many customers may come into one shop, and it's a common scenario. Have a look at the following example.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Client
{
class Customer
{
Shop s = new Shop();
public string CName { get; set; }
public Shop GetSetShop
{
get
{
return s;
}
set
{
s = value;
}
}
public void Print()
{
Console.WriteLine("customer Name:- " + this.CName);
Console.WriteLine("shop Name:- " + this.GetSetShop.ShopName);
}
}
class Shop
{
public string ShopName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Shop s = new Shop();
s.ShopName = "Computer World";
Customer a = new Customer();
a.CName = "Sourav";
a.GetSetShop = s;
Customer b = new Customer();
b.CName = "Ram";
b.GetSetShop = s;
a.Print();
b.Print();



Join the conversation! Your thoughts help the community grow.