Different way of creating keys in EFCodeFirst

  • Home
  • Blog
  • Different way of creating keys in EFCodeFirst

Recently I have been playing with Entity Framework Code First and I like it a lot. There are plenty of features given and you can configure all that stuff with code. I have already written couple of post for Entity Framework Code First.

Different way of mapping in EFCodeFirst

Entity Framework code first and Inheritance–Table per hierarchy
Entity framework code first and inheritance- Table Per Type As you EFCodeFirst generate database table based on the configuration defined in classes. Today we are going to learn about how we can create key with different configurations. By default Entity framework any field determine based on field name. So any first field which has Id in it’s name will be treated as primary key and it will auto increment primary key. So let’s take example of following class.

public class Student
{
    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Standard { get; set; }
}

Here it will create StudentId as primary key.

public class Student
{
    [Key]
    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Standard { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity().HasKey(t => t.StudentId);
    base.OnModelCreating(modelBuilder);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity().HasKey(t =>new { t.StudentId, t.FirstName});
    base.OnModelCreating(modelBuilder);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilderEntity()
        .Property(s => s.StudentId)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
public class Student
{
    [Key]
    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Standard { get; set; }

    [ForeignKey("DepartmentId")]
    public DepartMent Department { get; set; }
}

public class DepartMent
{
    [Key]
    public int DeapartmentId { get; set; }

    public string DepartmentName { get; set; }
}

That’s it. In this blog post I have written basic configuration of keys. Hope you like it. Stay tuned for more!!