Entity FrameWork Core Code First
Installing EntityFrameWordkCore
For Visual Studio
PM>> Install-Package Microsoft.EntityFrameworkCore.SqlServer
PM>> Install-Package Microsoft.EntityFrameworkCore.Design
For Visual Code
dotnet add package MySql.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
Create class Category
public class Category{
[Column("CategoryId")]
public short Id { get; set; }
[Column("CategoryName")]
[StringLength(128)]
public string Name { get; set; }
public List<Product> Products { get; set; }
}
Create class Product
public class Product{
[Column("ProductId")]
public int Id { get; set; }
[StringLength(128)]
[Column("ProductName")]
public string Name { get; set; }
public short CategoryId { get; set; }
public short ModelYear { get; set; }
public decimal Price { get; set; }
public Category Category { get; set; }
}
Create class BikeStoreContext
public class BikeStoreContext : DbContext{
public BikeStoreContext() { }
public BikeStoreContext(DbContextOptions<BikeStoreContext> options) : base(options) { }
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){
if (!optionsBuilder.IsConfigured){
optionsBuilder.UseSqlServer("Name=ConnectionStrings:BikeStore");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder){
modelBuilder.Entity<Category>().ToTable("Category", "production");
modelBuilder.Entity<Product>().ToTable("Product", "production");
}
}
Initial Migration
For visual studio
Add-Migration MigrationName
Update-Database
For visual code
dotnet ef migrations add InitialCreate --context PhoneMySqlContext
dotnet ef database update --context PhoneMySqlContext
Remove Migration
For visual studio
Remove-Migration
For visual code
dotnet ef migrations remove --context PhoneMySqlContext