Quotes .....

There never was, there never will be, a man who is always praised, or a man who is always blamed....

Saturday, November 9, 2013

MVC Ajax Search Form - Code First Migrations


1. Create an ASP.NET MVC 4 Web Application.








2. Select Basic Project Template, Razor View engine and leave ‘create a unit test project’ tick box blank.














3. Add a Model Class name it as Address.cs.











Shortcut: Ctrl+. To find references required
4. Add reference to jquery.














5. Create a connection string in the Web.config file.
<add name="AddressDBContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=PostCode;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\PostCode.mdf" providerName="System.Data.SqlClient" />
6. Build the solution (Ctrl+Shift+B).
7. Add a Controller named AddressController.































8. Add a View by right click in the AjaxSearch method in the AddressController.



















9. Create a partial view ‘_PostCodesList’ in the View/Address folder. Click the Create as a partial view tick box.

















10. Enable code first migrations.


At the PM> prompt enter the following command:
enable-migrations -contexttypename AddressDBContext









The Configuration class includes a Seed method that is called when the database is created and every time it is updated after a data model change.
namespace MvcSearchSite.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    using MvcSearchSite.Models;
    using System.Collections.Generic;

    internal sealed class Configuration : DbMigrationsConfigurationAddressDBContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(MvcSearchSite.Models.AddressDBContext context)
        {
            var postcode = new List<Address>
            {
                new Address { ID=1, PostCode = "AB101AB",   Street1 = "Alexander",
                    Street2 = "",Address1="Address1",Address2="",Town="Derby",County="Derbyshire" }
               
            };
            postcode.ForEach(s => context.Addresses.AddOrUpdate(p => p.ID, s));
            context.SaveChanges();
        }
    }
}
Build the project.
In the Package Manager Console window, enter the following commands: 
add-migration InitialCreate
update-database
A SQL Server database has now been created for your data model

In Database Explorer db is visible, sql commands can be executed.







If you need to add more data to the table, change the Seed method and run the ‘update-database’ command.











11. Set the default starting page in ‘App_Start/RouteConfig.cs’.










12. Run the application (F5)

No comments: