Code-First approach in EF Core, including migrations.

The Code-First approach allows you to define your database schema using .NET classes. EF Core uses these classes to generate the database schema.

Migrations:

  • Migrations are used to manage changes to the database schema as your model evolves.
  • They allow you to create and apply database updates without losing existing data.
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options) : base(options) { }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}
  • Use the Package Manager Console commands: Add-Migration InitialCreate and Update-Database to create and apply migrations.

Leave a Reply

Your email address will not be published. Required fields are marked *