Mar 27, 2018

ASP.NET Entity Framework 6 Code First Migrations - basics (.NET 4.6.2 standard)

Create empty Web application with MVC (.NET 4.6.2)
Add Entity Framework as NuGet package.
Create first model:

public class Person
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [StringLength(24)]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
    }
Run in Package Manager Console:

PM> enable-migrations
This will create Migrations folder with Configuration class. Enable auto migrations by changing this:

AutomaticMigrationsEnabled = true;

Create Context class. Here you must register all your models for database:

    public class AdresarContext : DbContext
    {
        public AdresarContext() : base("Adresar")
        {
        }
        public DbSet<Person> Persons { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
        }
    }
Run in PM console:

PM> update-database -verbose
This should generate Database with table(s).

Let's add extra table with master detail relationship.

New class:

public class City
    {
        [Key]
        public int Id { get; set; }
        [StringLength(25)]
        public string Name { get; set; }
        public ICollection<Person> Persons { get; set; }
    }
Reference it in Person:

 [Required]
        public City City { get; set; }

Register it in Context:

        public DbSet<City> Cities { get; set; }

Run update again:

PM> update-database -verbose



No comments:

Post a Comment