Thursday, June 13, 2013

One to many relationship in using C# class

In our daily project development life we frequently develop class which falls under one to many  relashionship. so those who still searching ,’how to implement one to many relationship in C# class my article is for them.

At first let’s explain “What is one to many relationship?”
Guys. I think already you are in job or at least searching job. Try to remember that day when you was filling up your profile in some job portal. And most probably you have given your preferred job location at least 2 or 3, right ?  And this is the example of one to many relationship.  Are you thinking  Why ?

Why not ?. You have created your profile , So profile owner is one person and you have chosen two location as your preferred job location. So one person is getting map with two location. –Now agree ?

Fine . Let’s have a look ,how to implement one to many location in C# class.  Here I have implemented Person class and it has only one property called Name. And also another property is there called PreferredLocation. It accept a object list of or collection of Preferredlocation class. Now with this property using the object of Person class we can assign more than one location against one person.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;

namespace BlogProject
{
    public class Person
    {
        public string Name {get; set;}
        public List<PrefferLocation> PreferredLocation { get; set; }

        public void ShowData(Person p)
        {
            Console.Write("Name:- "+ Name + "\n");
            Console.Write("Location List:- ");
            foreach (var V in p.PreferredLocation)
            {
                Console.Write(V.Location +" ,");
            }
        }
    }
    public class PrefferLocation
    {
        public string Location{get;set;}
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "Sourav";

            List<PrefferLocation> locList = new List<PrefferLocation>();

            PrefferLocation loc = new PrefferLocation();
            loc.Location = "Kolkata";
            locList.Add(loc);

            loc = new PrefferLocation();
            loc.Location = "Bangalore";
            locList.Add(loc);

            p.PreferredLocation = locList;
            p.ShowData(p);
            Console.ReadLine();

        }
    }
}




1 comment:

  1. Thanks for the explaination.

    How would you deal with many-to-many relationship?

    ReplyDelete