Fluent API vs Data Annotations Working with Configuration – Part 2


I hope, you have already learned very basic on Fluent API and Data Annotations in Part 1. And hope you have learned how to work with code first using Author and Book classes on previous article. We have decided to change the class name from Author to Publisher as Publisher and Book is more appropriate for One to Many relationship. Ok let’s start, Code First allows you to override its conventions by applying additional configurations. You can choose either attribute based data annotation or strongly typed Fluent API for those configurations. You have seen how how to override the OnModelCreating method. The DbModelBuilder that is provided to the OnModelCreating method is the class for adding configurations.

public DbSet Publishers { get; set; }
public DbSet Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
            modelBuilder.Entity<Publisher>()
                .Property(n => n.PublisherName).IsRequired();
            modelBuilder.Entity<Publisher>()
                .Property(d => d.Description).HasMaxLength(500);
            modelBuilder.Entity<Publisher>()
                .Property(p => p.Photo).HasColumnType("image");
            modelBuilder.Entity<Book>()
                .Property(n => n.BookName).IsRequired();
            modelBuilder.Entity<Book>()
              .Property(n => n.BookName).HasMaxLength(200);
}

So you know how to work with Required, Column Type check, Max Length. How to configure properties of a class. You can also configure the class itself. You can also specify that which database table it should map to:

modelBuilder.Entity<Publisher> ().ToTable(“Your_Desired_Table_Name);

It is possible to use both Data Annotations and Fluent API. If you use both together your code will become inconsistent. It is always advised that try to keep your code consistent. So use any one, either Data Annotations Or Fluent API.

Now, if you need lot of configuration to perform, the OnModelCreating method mighty quickly become overwhelmed with code. You can group configuration by entity within individual EntityTypeConfiguration classes and then call them.  Let us separate Book and Publisher. Add two classes: 1) BookConfiguration 2) PublisherConfiguration. Your classes should look like the following:

 public class BookConfiguration : EntityTypeConfiguration<Book>
    {
        public BookConfiguration()
        {
            Property(n => n.BookName).IsRequired().HasMaxLength(200);
        }
    }
 public class PublisherConfiguration : EntityTypeConfiguration<Publisher>
    {
        public PublisherConfiguration()
        {
            Property(n => n.PublisherName).IsRequired();
            Property(d => d.Description).HasMaxLength(500);
            Property(p => p.Photo).HasColumnType("image");
        }
    }

Calling modelBuilder.Entity<Book>() will actually create an EntityTypeConfiguration<Book> and return it to you, so whichever approach you choose, you are accessing the same API.

Now change your OnModelCreating method that consumes those two classes  you created earlier. Your code should look like the following:

  public class LibraryDB:DbContext
    {
        public DbSet<Publisher> Publishers { get; set; }  
        public DbSet<Book> Books { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new BookConfiguration());
            modelBuilder.Configurations.Add(new PublisherConfiguration());
        }
    }

Now you will learn how to recreate the database when the model change or to match the model to database. Before that, make sure you have installed EF latest version properly. You can use NuGet package manager for that. The Entity Framework can create, update, drop databases when application runs. The Entity Framework recommends to use “Database Migrations” as a prevention for loosing old records. But for production environment you always need to generate some test data. Entity Framework has “Seed” Method that allows you to seed some dummy data in the database. Lets have a look how to do that:

There are two methods for achieving your purpose , write any one of the following lines within Application_Start inside “Global.asax.cs” file. There is another good way to do that with dummy data. Add a new class named “DBInitializer” inherits from “DropCreateDatabaseIfModelChanges<LibraryDB>“.

   protected override void Seed(LibraryDB context)
            {
                //base.Seed(context);
                context.Publishers.Add(new Publisher
                {
                    PublisherName="O'Reilly",
                    Description="NA"
                });
                context.Publishers.Add(new Publisher
                {
                    PublisherName = "McGraw.Hill",
                    Description = "NA"

                });
               context.SaveChanges();
            }

Hope you all enjoyed. Have fun 🙂

Fluent API vs Data Annotations- Working with Configuration-Part1


If you consider the DDD architecture designs, one thing you must fulfill that is isolation our Domain Model Layer. To achieve that you must isolate Domain Entities from any other layers such as infrastructure layers, Data Persistence layers where you have a selected data technology. So you need to satisfy the  Persistence Ignorance Principle for domain Classes (Entities, Value-Objects, Domain Services, etc.). Here comes the question for right choice. This is the reason POCO entities are the right choice for DDD.

If you go further deep into Code First, you’ll see that the initial way to make the mappings from your POCO Domain Entities classes towards your final database tables is based on conventions. I have question ?? what will happen if those conventions are not ok (if you need to adjust to an existing database or whatever) ?? . So you need to customize those conventions. You can do that either in two ways. Let us start describing those two ways:

Code first leverages a programming pattern referred to as convention over configuration. Code first gives you two ways to add these configurations to your classes. One is using simple attributes called DataAnnotations within the ” System.ComponentModel.DataAnnotations “ namespace which is part of the .NET Frameworkand the other is using code first’s Fluent API, which provides you with a way to describe configurations imperatively, in code. Customizing it withFluent API is a way that fits much better with the PI (Persistence Ignorant), because our Domain Model will be ignorant of those mappings which will be defined into our Data Persistence Infrastructure layer, so, our Domain Model Layer will be better isolated from infrastructure implementation.

Everything what you can configure with DataAnnotations is also possible with the Fluent API. The reverse is not true. So, from the viewpoint of configuration options and flexibility the Fluent API is “better”. Learning the Fluent API is almost a Must , the DataAnnotations are a nice-to-have for simple applications.

We will describe the example for MVC4 Code First application.

public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public virtual ICollection<Book> Books { get; set; }

}

public class Book
{
public int BookId { get; set; }
public string Name { get; set; }
public DateTime PublishDate { get; set; }
public Author Author { get; set; }
}

public class LibraryDB:DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
}

The Author and Book class describes a particular Author might have collection of Books. So Author object can have one or more Books associated with it. Our class LibraryDB, will inherit from DbContext in order to gain all of DbContext’s capabilities. Additionally, it will expose properties that return queryable sets, DbSets, of Author class and Book classe. The last class represents a complete data layer that you can use in applications. For DbContext you will be able to query, change, track and save Author and Book data. Thanks to DbContext :).

Let’s start with the Author Author class. There are three things I would like to change:

Ensure the Name is provided.

Limit the max length of Description field to 500 characters.

Store the Photo into SQL Server image type.

We need “System.ComponentModel.DataAnnotations” assembly that is part of .NET 4.0. Apply the following code:

public class Author
{
public int AuthorId { get; set; }
[Required]
public string Name { get; set; }
[MaxLength(500)]
public string Description { get; set; }
[Column(TypeName=”image”)]
public byte[] Photo { get; set; }
public virtual ICollection<Book> Books { get; set; }

}

public class Book
{
public int BookId { get; set; }
[Required]
public string Name { get; set; }
public DateTime PublishDate { get; set; }
public Author Author { get; set; }
}

The Required annotation needs no additional information, whereas the MaxLength and Column have parameter information that you need to provide. The parameter provided to the Column annotation is specific to the database that you are mapping to. We want to store Photo in a SQL Server image field. So we configured the data type. All three annotations will impact the databse schema. On the Book class we have only placed the required annotaion no character limit, so in the database schema you will find the length is nvarchar(max). Note that, we can also use MinLength which is an interesting annotation. While MaxLength has a database counterpart, MinLength does not. MinLength will be used for EF validation without impacting the database.

MinLength is the only configuration that can be achieved using Data Annotation but has no counterpart in the Fluent API configurations.

If you opened up the database table you will find the changes that we have made in our classes. We will discuss on EF DataBase Migration later.

Configuring with Fluent API:

The concern of a Fluent API isn’t specific to Code First or the EF. The basic is chained method calls to produce code that is easy for the developers to read. The return type of each call then defines the valid methods for the next call. There are more reasons why developers like Fluent API.

public class LibraryDB:DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Author>()
.Property(n => n.Name).IsRequired();
modelBuilder.Entity<Author>()
.Property(d => d.Description).HasMaxLength(500);
modelBuilder.Entity<Author>()
.Property(p => p.Photo).HasColumnType(“image”);
modelBuilder.Entity<Book>()
.Property(n => n.Name).IsRequired();
}
}

Let us describe the mechanism above code, how it works actually. Julia Lerman & Rowan Miller describes nicely in their “Programming Entity Framework Code First” book. “When its time to build the model, the DBContext first looks at the classes and learns what it can from them. At this point, the context is ready to reason out the model, but there is an opportunity for the developers to interrupt the context and perform additional configuration. DbContext.OnModelCreating method called by the context just before the model is built. The method is virtual, so you can override it and insert your own logic. This is where the Fluent API configuration goes”.

Stay Tuned: Be Right Back with more advanced…