Create empty Web application with MVC (.NET 4.6.2)
Add Entity Framework as NuGet package.Create first model:
public class PersonRun in Package Manager Console:
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(24)]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
PM> enable-migrationsThis 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 : DbContextRun in PM console:
{
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>();
}
}
PM> update-database -verboseThis should generate Database with table(s).
Let's add extra table with master detail relationship.
New class:
public class CityReference it in Person:
{
[Key]
public int Id { get; set; }
[StringLength(25)]
public string Name { get; set; }
public ICollection<Person> Persons { get; set; }
}
[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