Friday, 16 November 2012

How to write Relationships in Code First?


Yes, Code First Entity Framewok supports relationships like Database First/Relational databases now

Entities :

public class Employee
    {
        [Key]
        public int Eid { get; set; }
        public string Ename { get; set; }
        public string EPhone { get; set; }
        public int Eaddress { get; set; }     
        public Departments Dept { get; set; }

    }
    public class Departments
    {
        [Key]
        public int Did { get; set; }
        public string DName { get; set; }

    }

Here:

Departments----PK table
Employee----Fk table
Primary keys are autogenerated if we send also those are ignored.
Eaddress(reference Departments)à is a reference key of Departments table.  as well we can specify the Department also at a time
Ex:
   Employee eobj = new Employee { Dept = new Departments { DName = "Accounts" },

            Ename = "raju", EPhone = "7171" };

            con.emps.Add(eobj);

            con.SaveChanges();
 


Eid          Ename  EPhone                Eaddress
1              raju        7171       1

Did         DName
1                     Accounts

Employee is automatically mapped to dept of 1
  Employee eobj = new Employee {  Eaddress=1, Ename = "raju1", EPhone = "7172" };

What is use of   public int Eaddress { get; set; }      in Employee ?

New employee -----belongs to existing Department.


Eid          Ename  EPhone                Eaddress
1              raju        7171       1
2              raju1      7172       1  // newly employee added to  existing department.
Did         DName
1                     Accounts
And
We can add new Department aswell new employee at a time.
    Employee eobj = new Employee { Dept = new Departments { DName = "Sales" }, Ename = "balu", EPhone = "4131" };

Eid          Ename  EPhone                Eaddress
1              raju        7171       1
2              raju1      7172       1
3              balu       4131       2
Belongs
Did         DName
1              Accounts
2              Sales
 how to specify keys in Code-First model:
             modelBuilder.Entity<Employee>()
               .HasRequired(a => a.Dept)
               .WithMany()                     --à type of relationship
               .HasForeignKey(u => u.Eaddress);

            //modelBuilder.Entity<Employee>().
                              
            base.OnModelCreating(modelBuilder);

NOTE: keep in mind -à data will be splicted as per columns and stored in their relavent tables.

No comments:

Post a Comment