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 !!


Sunday, May 31, 2015

Installing/Updating Entity Framework


Open a New project of your choice(MVC,Web Application, Console Application.) in visual studio. I have taken MVC4 Internet Application as example. The following procedure and the implementation explained later applies for all project types.

Right Click on the project in solution explorer and select "Manage NuGet Packages".


Click "Install" or "Update" against "Entity Framework".



Once done, Entity FrameWork will be installed/updated and added to your project reference.

Friday, May 29, 2015

Entity FrameWork Code First - Introduction


Code First approach was introduced with Entity Framework 4.1. With code first, you can start building your classes based on your business requirement first and entity framework will take care of creating the databases and tables. (If you don't want your databases to be automatically created, you can turn off this feature).

Why Code First ?

Though Database First/Model First approaches seem to be effortless at the beginning, it becomes difficult when you want to have more and more customization to your properties/database columns. With these approaches, .edmx model files will be auto-generated. Yes, it seems to have taken care of most of your job. But you can never alter these files, because any changes that you make will be lost when you regenerate the model files again for some reason.(eg. adding a column).  For example, if you want to have a different display name for a column (rather than the one in the database), you will have to create a partial class and extend your model class. You have to do this for almost every model that you are creating.

But with code first approach, you have more control over customizing your columns(making it a required field/read only etc..) as the model that you hand code becomes your database. You can precisely and easily specify the relationship and the constraints. Most of all, Entity Framework provides an excellent version control of your database which will otherwise be cumbersome.

When you are planning to create a small project, you can very well use database/model first approaches as it will greatly reduce your time. But for mediocre to big projects, code first is always a recommended approach.

Next>> Installing/Updating Entity Framework

Wednesday, May 27, 2015

Changing DefaultConnection to Sql Server DB in Auto generated MVC code

When "Internet Application" is chosen as template for MVC4 Web Application, we can see the auto generated code for the home page including user login logic. The tables will be created in the local DB instance in Visual studio in MDF file format as shown below.
But if you wish to store the data in your database in sql server, you have to make the following modifications.

1. Add your connection string in web.config file.

  <connectionstrings>

    <!-- <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-Triczz-20150512151642;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-xxxx.mdf" providerName="System.Data.SqlClient" /> -->


   <add name="SomeConnectionName" connectionString="Data Source=.\SQLEXPRESS; Database=YourDB; Integrated Security=SSPI" providerName="System.Data.SqlClient" />


  </connectionStrings>


  
You can remove the "DefaultConnection" string commented above,

2. In AccountModels.cs, UsersContext uses "DefaultConnection".


Change "DefaultConnection" above to "YourDB" that you gave in web.config file. Or you can even pass the name of the connection string as :base(name="SomeConnectionName")

3. In WebSecurity.InitializeDatabaseConnection the connection name should be changed. It can be found in Global.asax or InitializeSimpleMembershipAttribute.cs in Filters folder.

Change the "DefaultConnection" to "SomeConnectionName" that you gave in web.config file.


Once the above changes are made, run the project to see the "UserProfile" and the other tables being created in the specified database.

History of C#


1-C# History