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'.


Configuring with Data Annotation Vs Fluent API

Entity Frame Work automatically detects many configuration that you are trying to make if you follow some default set of rules. We will be seeing those default rules (or conventions) in detail in the upcoming posts. But there might be lot more that you want to configure which should be explicitly mentioned. For example, you might want to make a column as 'not null' in the database. To accomplish such configurations, we can make use of data annotations approach or fluent API approach.

Configuring with Data Annotations:

Data annotation is the simple and easy way of configuring your database. Data annotations are the attributes that you specify directly to the properties of your domain class or to the class itself. You must include System.ComponentModel.DataAnnotations namespace before using them in your class.

Consider the following example.

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

In order to make "Name" as "not null" in the database, we have to simply decorate it with [Required] attribute. [Required] is one of the data annotations provided by entity framework. 

Many developers prefer data annotations approach for configuration. But, most of the configuration can be done with this approach and not all. Also, you might not want to use this approach if you want to have a cleaner domain class file. i.e if your model class should only contain properties and not flooded with too many attributes in between, which makes it quite unreadable. In such cases, you can prefer fluent API.

Configuring with Fluent API

Dbcontext class  exposes a method called "OnModelCreating".  For using Fluent API approach, you should override this method in your context class. This method involves chain of method calls that makes the code more readable.


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Parent>()
                              .Property(p => p.Name).IsRequired();
    }

Here, we are trying to say to Entity Framework - " Hey, find an entity named "Parent" and check the properties of the parent entity to find "Name" property and finally make it a required field". 

Monday, June 1, 2015

Simple Code First Example

To begin with code first, let us try to create a single table in the database. You just have to code the following.

1. A class file which is a representation of your business layer. i.e, Add a class with  column names of your table as properties of the class.

For MVC Applications, Right click on the models folder and select "Add -> ADO .NET Entity data model" and give a name for your model. You can create the following class within the model file. For other types of applications (other than MVC), simply add a class file to your project.

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

Here, "Parent" is the table name and "Id" &"Name" are the table columns.

2. A context file that inherits from "DbContext". DbContext is a built-in class of Entity Framework that helps us to query the database  and interact with it. 

    public class SampleContext : DbContext
    {
        public SampleContext()
            : base("name=DefaultConnection")
        {
        }
        public DbSet<Parent> Parents { get; set; }
    }

Here, we are passing "DefaultConnection" to the constructor which is the name of the connection string in web.config file. Web.config will be auto-generated for MVC internet applications. You can also specify your own database instead of default connection as mentioned here. For other applications you can add your own connection string in web.config file and pass the name of the connection in the constructor. Instead of giving "name=", you can directly pass the database name to the constructor (:base("sample")) or you can also leave it empty. If you don't specify anything, a database with name {namespace}.{context class name} will be created in your local SQLEXPRESS.

We have added another property called "Parents" to the context class and note that it is returning DbSet<parent>. This property is going to help us in querying the database. "DbSet" is a collection of entity set. In this case, "Parent" is our entity. You will be more clear when we actually use this property.


Now we are done with our model creation. We just have to create an instance of context class and then we can start interacting with the database.

   public void Create()
   {
       SampleContext db = new SampleContext();    
       Parent parent = new Parent(){Name="XYZ"};
       db.Parents.Add(parent)
       db.SaveChanges();
   }

Add the above code to your controller (for MVC) or main method(for other applications). First, we are creating an instance of context class. Then, collecting the data that we want to save to the database. In the next step, we are using the "parents" property created in the context class to add the values to the database and finally saving it.

Once you run your project you can see the table created in your database.


Table with name "Parents" has been created in the database(Table name is automatically pluralized by entity framework). Without any ado .net code, we have created our table with the help of entity Framework code first approach !!