Code First!!!

Code first- I just love this approach, well any developer would. MVC has been haunting since long ago. So thinking to my self better late than never gave it shot and found it to be pretty neat & interesting. And Microsoft as before with MVC, Entity framework, etc etc leaves you wondering how they did that!!! .

Lets start coding (if we get a chance to ;) ),

Select ASP.NET MVC3 Web Application






in the next select Internet application and try razor view engine with html5













Now check your solution explorer you will see quite a lot of things that has come from thin air. Don't b shocked there is still to come


















Microsoft now needs a developer who knows to create a class
For this sample project let me create following two classes Employee and Department and add to Models folder


    public class Employee
    {
        public int Id { getset; }
 
        public string Name { getset; }
 
        public string EmailId { getset; }
 
        public int DepartmentId { getset; }
 
        public Department Dept { getset; }
    }



    public class Department
    {
        public int Id { getset; }
 
        public string Name { getset; }
 
        public ICollection<Employee> Employees { getset; }
    }


Then we will change to connection string to the database we want to point to. In this sample i will be pointing to Company.sdf  in App_Data folder.(If the database does not exists it will be created)


  <connectionStrings>
    <add name="ApplicationServices" connectionString="Data Source=|DataDirectory|Company.sdf;" providerName="System.Data.SqlServerCe.4.0"/>
    <add name="DataServicesContext" connectionString="Data Source=|DataDirectory|Company.sdf;" providerName="System.Data.SqlServerCe.4.0"/>
  connectionStrings>
Now we are with the Models lets right click on the controller and controllers for the models we created.













Yes we got wizard for that too. Once the wizard is started all the magical spells create the rest of your project, from the view to the contoller including basic validations on the fields.

Run the project and checkout the view that was automatically created. for example lets see http://localhost/employee/create, you can see that the for the foreign key relation that was defined in class structure  appears as a combobox.


















Thanks to microsoft for making things simpler. The only thing that we had to do in this demo was to create two classes Department & Employee and point the connection string right. There are a still lot of things that i don't yet know hope to catch up with the microsoft ;) .

In MVC url routing has been made pretty easy and neat. and data annotations using attributes eliminates quite a lot of lines of code.

Comments

Popular posts from this blog

Launch .Net Core with VSCode for starters

Google Maps

Protecting sensitive data using Secret Manager in .Net Core