Monday, August 25, 2014

Basic Entity Framework Code First Conventions

1) Entity Framework Code First pluralizes the tables names. For example: if the class name is Student then Code First creates a table with name Students.

Code First uses Entity Framework's Pluralization Service to pluralize the table names.


If you want to remove the table naming convention, you can do that by overriding the OnModelCreating() method like follows:

using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db;

protected override void OnModelCreating(ModelBuilder modelBuilder)
{    
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
2) By default each table is created with dbo schema.

3) The column names are same as the class property names. For example: if there is a property named FirstName in the Student class then Code First creates a column with name FirstName in the Students table.


4) Any property of the class with name "Id"(case insensitive) or {class name} + "Id" will be treated as primary key in the table. In the Student.cs class file if there is a property with name Id or StudentId then it will be treated as the primary key in the Students table.


5) For string properties, by default, Code First creates a Nullable column with data type nvarchar(max) in MS SQL Server. For example, if the Student.cs class file has a property FirstName which is of type string then Code First create a column named FirstName(null, nvarchar(max)) in the Students table.


6) One-to-many relationship convention: Let's assume we have two entities Student and Standard and the supporting classes are Student.cs and Standard.cs. There is one-to-many relation between Standard and Student. So one Standard contains many Students and one student can belongs to only one standard.


Convention for creating the foreign key is : <Navigation Property Name>_<Primary key of the related class>


Example:

    public class Student
    {
        public int Id { getset; }
        public string Name { getset; }
        public virtual Standard Standard { getset; }
    }
   public class Standard
    {
        public Standard()
        {
            Students = new List<Student>();
        }
 
        public int StandardId { getset; }
 
        public string Name { getset; }
 
        public ICollection<Student> Students { getset; }
    }
Here note that we don't have any foreign key column in the Student class. So Code First creates a foreign key column with name = {NavigationProperty Name}_{Primay key property name} i.e Standard_StandardId in Students table.

The generated columns are:





The generated SQL(for MS SQL Server) for Students table is:
CREATE TABLE [dbo].[Students] (
    [Id]                  INT            IDENTITY (1, 1) NOT NULL,
    [Name]                NVARCHAR (MAX) NULL,
    [Standard_StandardId] INT            NULL,
    CONSTRAINT [PK_dbo.Students] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_dbo.Students_dbo.Standards_Standard_StandardId] 
 FOREIGN KEY ([Standard_StandardId]) REFERENCES [dbo].[Standards] ([StandardId])
); 
 
GO
CREATE NONCLUSTERED INDEX [IX_Standard_StandardId]
    ON [dbo].[Students]([Standard_StandardId] ASC);
 
The generated SQL for Standards table is:
CREATE TABLE [dbo].[Standards] (
    [StandardId] INT            IDENTITY (1, 1) NOT NULL,
    [Name]       NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_dbo.Standards] PRIMARY KEY CLUSTERED ([StandardId] ASC)
);
 

Sunday, August 24, 2014

Create First Model Using Code First Conventions

Code first leverages a programming pattern referred to as convention over configuration.

If you follow the conventions correctly then Entity Framework will create the models correctly without any additional information. But if you don't follow the convention then you need to provide additional information to Entity Framework to create the models.

Let's create a simple Student class as follows:
namespace CodeFirstIntroduction.Data.Models
{
    public class Student
    {
        public int Id { getset; }
        public string Name { getset; }
    }
}

Here the Student class contains two properties: Id and Name. Entity Framework Code First treats "Id" as the primary key of the Student table as per the convention.

The convention is: Any table which property name is "Id"(case insensitive) will be the primary key or any property with name "class name + Id"(case insensitive)e.g. StudentId will be the primary key. If no such convention found then it will throw an exception during runtime for missing primary key.

To start using Code First, we need to create a class which will inherit from DbContext. See the next example:


using System.Data.Entity;
 
namespace CodeFirstIntroduction.Data.Models
{
    public class EducationContext : DbContext
    {
        public DbSet<Student> Students { getset; }
    }
}

Here the EducationContext class is inherited from DbContext which contains a property Students which is of type DbSet<Student>. Like the DbContext, the DbSet is a wrapper around the ObjectSet

Let's use the EducationContext to add a student information to Students DbSet as follows:


        using (var context = new EducationContext())
           {
               context.Students.Add(new Student
               {
                   Name = "Dukhabandhu Sahoo"
               });
 
               context.SaveChanges();
           }

When first time the application runs and the above code is executed then Entity Framework creates a database for you even if there is no connection string mentioned. If you are using it in a Web Application then a file named CodeFirstIntroduction.Data.Models.EducationContext.mdf will be added to the App_Data folder. If you note the name is the fully qualified name including the namespace and class name. It creates two tables: _MigrationHistory and Students.

Students tables is created as we have created DbSet<Student> Students property inside the EducationContext class. The _MigrationHistory(previously it was named EdmMetadata table till EF 4.2) table is created by Entity Framework to keep track of the changes happened to the database. The following image displays the actual database and tables created by the EducationContext.



Friday, August 22, 2014

Introduction to Entity Framework Code First

The first version of entity framework was released in DOT NET framework 3.5. Entity Framework has 3 different workflows(i.e. ways to create the model). These are: Code First, Database First, and Model First.

Entity Framework Code First was introduced in EF 4.1.

Code First allows you to create the model from your existing POCO(Plain Old CLR Objects) classes.

Developers don't need to wait till the database is ready to start coding. They can start coding by creating classes as their need which will be converted to tables later by Entity Framework. The conversion of classes to tables will vary depending upon the data annotation attributes assigned or mappings specified by FluentAPI.

Code First, Database First and Model First are only different ways to create model for data access. Once the models are created, Entity Framework runtime behaves the same regardless how you created the model.

The following diagram will help you to select the correct approach of creating model.



(Image source: Programming Entity Framework: Code First by Julia Lerman and Rowan Miller)

So if you want to create model from code(i.e from POCO classes) you can choose Code First irrespective of new or existing database.

If you want to create model from designer(i.e from EDMX file) you have two options: if new database then you can pick Model First else if existing database then Database First.

DbContext


DbContext is the light-weight version on Entity Framework's ObjectContext. DbContext is the core of Code First API.

Microsoft found some of the features of ObjectContext are not used by developers in their daily programming life. So Microsoft's Entity Framework team has simplified the ObjectContext to DbContext which contains the simple methods and properties.