Sunday 30 November 2014

Configure One-to-Many Relationship:

We are going to configure a One-to-Many relationship between Student and Standard, as many students are studying in one standard.

Configure One-to-Many relationship using DataAnnotation:

Student entity class has a reference property of Standard class with StandardId foreignKey property and Standard class has a collection property for Students. So this DataAnnotation will result in a One-to-Many relationship.
     
    public class Student
    {
        public Student() { }

        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }

         public int StdandardId { get; set; }
        
        public virtual Standard Standard { get; set; }
    }
        
    
    public class Standard
    {
        public Standard()
        {
            StudentsList = new List<Student>();
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }
        

Configure One-to-Many relationship using Fluent API:

Suppose your Student and Standard entity class doesn't follow Code-First conventions and they have different property names, for example:
   
    public class Student
    {
        public Student(){ }

        public int StudentId { get; set; }
        [Required]
        public string StudentName { get; set; }

        //StdId is not following code first conventions name
        public int StdId { get; set; }

        public virtual Standard Standard { get; set; }
    }
        
    
    public class Standard
    {
        public Standard()
        {
            StudentsList = new List<Student>();
        }
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }

        public virtual ICollection<Student> StudentsList { get; set; }
    }
        
So you can use Fluent API to configure a One-to-Many relationship between the Student and Standard entity classes:
    
   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            //one-to-many 
            modelBuilder.Entity<Student>().HasRequired<Standard>(s => s.Standard)
            .WithMany(s => s.StudentsList).HasForeignKey(s => s.StdId);

    }
        
Another possible way:
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
            //one-to-many
            modelBuilder.Entity<Standard>().HasMany<Student>(s => s.StudentsList)
            .WithRequired(s => s.Standard).HasForeignKey(s => s.StdId);
    }
        
The code shown above will create the following database:
one-to-one relationship in code first
The Entity Data Model in the designer will appear like the diagram shown below:
one-to-one relationship in code first

Getting Started With Asp.NET MVC 4 And Entity Framework

Asp.NET MVC framework has upgraded itself rapidly and a lot of whole features are being added/supported. I lastly worked with Asp.NET MVC 3 With LinQ Based Web Application. While checking out the MVC 4, I got familiar with Entity framework and MVC 4’s new look and feel etc. That’s why I have decided to share my first experience with Asp.NET MVC 4 And Entity Framework based web application development basics so that readers can have more easier start with these. I am using visual studio 2010 and SQL server 2008 as development environment of this exercise.
If you are an previously familiar with Asp.NET MVC, you might want to read the new mobile features and other features improvement/addition details.

Download And Install MVC 4:

First, we will need to set up our visual studio to work with asp.net MVC 4 . Download it from official site. Since Microsoft .NET platform introduced web platform installer, I find it very easy to get new product/patch/update installed and integrated very easily. As soon as it is done, we can move ahead to create our new exercise project with Asp.NET MVC 4 And Entity Framework.

The Exercise Project Background:

Did you ever think in total how many websites you signed up with? How many password combinations you used on all those sites? Can you remember the password of a site that you visited several months ago? Well, I did fell in this kind of issues several times. From this the idea came that an application be developed which will contain all these password information in a useful and organized way.
What about security? Why people will believe this application? Yeah, I know, don’t get too serious about it :D. Even so far, I don’t made a strict plan yet. Just let’s make the assumption for this tutorial at this moment.

Create New Project:

creating new project is similar to previous MVC 3 version. We will need to specify template engine, tell whether to create test project or not etc. After creation, a basic structure is already given. If we run this, we will see the home page like as follows:
Asp.NET MVC 4 HomePage

Lets Start With Creating A Model Class:

if you are already a Asp.NET MVC developer, you might know that, it is possible to scaffold a controller and views from a defined model. That’s why, we will start with defining a model class which will be used to create controller/views automatically. In our projects ‘Models’ directory, create a new C# class as follows:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
 
namespace MyPasswords.Models
{
    public class Password
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Category { get; set; }
        public string URL { get; set; }
        public string AppUserName { get; set; }
        public string AppPassword { get; set; }
    }
 
    public class PasswordDBContext : DbContext
    {
        public DbSet<Password> Passwords { get; set; }
    }
}
As you can notice here, we have created two classes one for the database table/entity with name ‘Password’ and another one is for DbContext which will act as the database container in our application. When you will create more tables, you can create this DbContext class separately as well.

Create Controllers And Views:

to create a new controller from the above created model, right-click on the ‘Controllers’ directory and use ‘Add’ -> ‘Controller’ option.
create new controller
It will lead you to a new controller creation window where you will be able to select the model class and DataContext class to be mapped with and template engine as well. Set them as in the image below.
New Controller Window
By defining the view template, we are creating views at the same time of controller creation, instead of creating them separately.

Connect To Database Server:

As we have create controller/model/views, its time to connect to the database server. In your web.config file, add a new connection string as below:
1
<add name="PasswordDBContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyPasswords;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
Name it with your DBContext class and set server/database name as per your own preference. Notice that, we haven’t created any database on our SQL server yet. Yes, and it’s not required at all. Here is the magic of Entity framework, it facilitates us to create database/tables from the defined entity automatically without worrying to do that manually via SQL management studio.

Build And Run Our Asp.NET MVC 4 And Entity Framework Based Mini Application:

so, if you have done all the steps as above properly, you should now be able to build the application successfully and run properly as well. After running use the URL “http://localhost:{port}/Password” to navigate to our recently implemented controller:
Controller Index Page
Here you can test the create new/update/delete all options whether they are functional or not ( They should be :) . Now if you go and check your database you should find it created properly on SQL server database:
Updated SQL Server DB

Preparing For Future Modification:

So, far we have done a good job. Now, what if we need to add a new entity to the database or modify an entity? As database is already exist, entity framework won’t go to create or modify it of its own. So, lets prepare for such scenario so that we can update our database in future whenever a new modification occurs, right from visual studio environment, easily.
Here, I am happy to introduce you with visual studio’s Package manager console, if you are not familiar already. Use visual studio’s ‘Tools’->’Library Package Manager’->’Package Manager Console’ to launch this console.
First use the “Enable-Migrations” command in the console and you should have an output as below:
1
2
3
PM> Enable-Migrations -ContextTypeName MyPasswords.Models.PasswordDBContext
Checking if the context targets an existing database...
Code First Migrations enabled for project MyPasswords.
Now Execute ‘Add-Migration’ command, which will create a scaffold template from your entity. Output should be as follows:
1
2
3
PM> add-migration Test
Scaffolding migration 'Test'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration 201302260652175_Test' again.
As you can see here, when we will make changes in our model entities, we will have to run this command again specifying the generated template name. The template file should look something like as follows:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
namespace MyPasswords.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
     
    public partial class Initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Passwords",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Title = c.String(),
                        Category = c.String(),
                        URL = c.String(),
                        AppUserName = c.String(),
                        AppPassword = c.String(),
                    })
                .PrimaryKey(t => t.ID);
             
        }
         
        public override void Down()
        {
            DropTable("dbo.Passwords");
        }
    }
}
Now lets execute the ‘update-database’ command which will make necessary changes to database:
1
2
3
4
5
PM> update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying code-based migrations: [201302260652175_Test].
Applying code-based migration: 201302260652175_Testl.
Running Seed method.
And we are done with database update completely :) . I like this feature a lot and I think, other developers should also as it will save a lot time to set up/modify database.

Angular Tutorial (Update to Angular 7)

As Angular 7 has just been released a few days ago. This tutorial is updated to show you how to create an Angular 7 project and the new fe...