Tuesday, June 2, 2015

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

No comments:

Post a Comment