Tuesday, June 2, 2015

Primary Key in code First

Default Convention

Entity Framework automatically detects your primary key if you specify {id} as the name or {typename}+{id} as the name(not case sensitive)

For example,

    public class Parent
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Here, 'Id' property will be automatically detected as primary key by entity framework. It detects even if you give 'ParentId' instead of  'Id'. Also, you can use any primitive type other than integer for primary key(like Guid).

Using DataAnnotation

If you want to give your primary key some other name, you can specify that by [Key] attribute (present in System.ComponentModel.DataAnnotations namespace).

For example,

    public class Parent
    {
        [Key]
        public int PId { get; set; }
        public string Name { get; set; }
    }

Using Fluent API

In Fluent API, we have to add primary key by using 'HasKey' method as shown below.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Parent>()
                              .HasKey(p => p.PId);
    }

With any of the above approach, you can make your property as primary key in the data table and it will be set as 'not null'.


No comments:

Post a Comment