Wednesday 15 April 2015

Many to many relationship in entity framework code first

Here we will learn Many-to-many relationship in entity framework code first.
In previous tutorial we took example on Student and StudentClasses and made many-to-many using DataBase first approach. We will continue this tutorial with this example.

Step 1: Add a another class file to the project, and give  Name it Classes.cs. write below code.
namespace EntityRelationShip
{
    public class Class
    {
        public string ClassID { getset; }
        public string  ClassName { getset; }
          public IList<Student> Students { get; set; }

    }
}

Step2: Go to your application and Add a class (Student.cs) file to your application.

namespace EntityRelationShip
{
    public abstract class Student
    {
        public int ID { getset; }
        public string StudentName { getset; }
         public IList<Class> Class { get; set; }
    }
}

Step(3)  : Add a new class for giving DBContext and write below code. And give the name for this class is StudentDBContext.cs.
using System.Data.Entity;
namespace EntityRelationShip
{
    public class StudentDBContext : DbContext
    {
        public DbSet<Class> Courses { getset; }
        public DbSet<Student> Students { getset; }

        protected override void OnModelCreating(DbModelBuilder _model)
        {
           _model.Entity<Student>()
            .HasMany(t => t.Class)
            .WithMany(c => c.Students)
            .Map(C =>
            {
                c.ToTable("StudentClass");
                c.MapLeftKey("StudentID");
                c.MapRightKey("ClassID");
            });

            base.OnModelCreating(_model);
        }
    }
}


Step(4) : Add connection string to the Web.Config file
<connectionStrings>
  <add name="StudentDBContext"
        connectionString="server=.; database= EntityRelationShip; integrated security=SSPI;"
        providerName="System.Data.SqlClient" />
</connectionStrings>


Step 6: Right click on your application and add a webform to the project.
<div style="font-family: Arial">
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <br />    
</div>

Now write below code in Code-Behind file.
using System;
using System.Linq;

namespace EntityRelationShip
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            StudentDBContext _student = new StudentDBContext();

            GridView1.DataSource = (from student in _student.Students
                                    from c in student.Classes
                                    select new
                                    {
                                        StudentName = student.StudentName,
                                        ClassName = c.ClassName
                                    }).ToList();

            GridView1.DataBind();
        }
}

Step 7: First delete “EntityRelationShip” Database in SqlServer if you have it.

Step 8: Now Run the application. At this time your database and your table will be created.
Step 9: Copy and pest below query.
Insert into Classes values ('Seven')
Insert into Classes values ('Eight')
Insert into Classes values ('Nine')
Insert into Classes values ('Tenth')
GO

Insert into Students values ('Munesh')
Insert into Students values ('Rahul')

GO

Insert into StudentClasses values (1, 1)
Insert into StudentClasses values (1, 2)
Insert into StudentClasses values (2, 1)
Insert into StudentClasses values (2, 2)
Insert into StudentClasses values (2, 3)
GO



Now your Application and check your data in gridview.

Many-To-Many relationship in entity framework

Here we will learn many-to-many relationship in entity framework(EF) with database first approach.
Many to many relationship means suppose there is school registration site which contain multiple students and students can contain many classes. In general we can say that Many-to-Many relationship require a join b/w tables .
We will understand this with an example
(1)First copy below script and Write query and insert some values to these tables.
Create Table Classes
(
     ClassesID int identity primary key,
     ClassesName nvarchar(50)
)
GO

Create Table Students
(
     StudentID int identity primary key,
     StudentName nvarchar(50)
)
GO

Create Table StudentClasses
(
     StudentID int not null foreign key references Students(StudentID),
     ClassesID int not null foreign key references Classes(ClassesID)
     primary key (StudentID, ClassesID)
)
GO


Insert into Classes values ('Seven')
Insert into Classes values ('Eight')
Insert into Classes values ('Nine')
Insert into Classes values ('Tenth')
GO

Insert into Students values ('Munesh')
Insert into Students values ('Rahul')

GO

Insert into StudentClasses values (1, 1)
Insert into StudentClasses values (1, 2)
Insert into StudentClasses values (2, 1)
Insert into StudentClasses values (2, 2)
Insert into StudentClasses values (2, 3)
GO


(2)Go to your application and right click on solution explorer and add a ADO.Net Entity data Modal and select Database first approach if we generate entity then only 2 entity will generate for Student and classes with many-to-many relationship b/w them. Now if we  see entity navigation property to navigate from classes to Students and from Students to classes.

(3)At this point right click on Many-to-Many association and click on Table mapping in mapping screen s many-to-many association is mapped to StudentsClasses.

(4)Right click on you application and add a webform and drag and down a Gridview from toolbox and write below code at the Page_Load event of this web form.
StudentDBContext _studentDBContext = new StudentDBContext();

    GridView1.DataSource = from student in _studentDBContext.Students
                            from classes in student.Classes
                            select new
                            {
                                StudentName = student.StudentName,
                                ClassName = Classes.ClassName
                            };
    GridView1.DataBind();
}



Now Run your application you will see respective data in gridview. 

C# program Selection Sorting

Selection sort is a straightforward sorting algorithm. This algorithm search for the smallest number in the elements array and then swap i...