Entity Framework

Recipes

  • Generate migration from Package Manager Console

      Add-Migration -Name "MigrationName" -OutputDir "Migrations" -Project EFProj
      Update-Database -Migration "MigrationName" -Project EFProj
      Remove-Migration -Force -Project EFProj
    
  • multiple column index with OnModelCreating

      class SomeEntityContext : DbContext {
          protected override void OnModelCreating(ModelBuilder modelBuilder) {
              modelBuilder.Entity<MultiKeyIndexEntity>()
                      .HasIndex(u => new { u.Id1, u.Id2, u.SomeReference})
                      .IsUnique();
          }
      }
    
  • multiple column index by adding a separate migration
      public partial class OrderTableBrandIdMerchantIdOrderReferenceUniqueIndexAdded : Migration {
              protected override void Up(MigrationBuilder migrationBuilder) {
                  migrationBuilder.CreateIndex(
                      name: "IX",
                      table: "SomeTable",
                      columns: new[] { "Id1", "Id2", "SomeReference" },
                      unique: true);
              }
    
              protected override void Down(MigrationBuilder migrationBuilder) {
                  migrationBuilder.DropIndex(
                      name: "IX",
                      table: "SomeTable");
              }
          }
    
  • A Model Snapshot is the current state of the model stored in a class file named {YourContext}ModelSnapshot.cs

      [DbContext(typeof(SomeEntityContext))]
      partial class ShippingEntityContextModelSnapshot : ModelSnapshot {
          protected override void BuildModel(ModelBuilder modelBuilder) {
              modelBuilder.Entity("EFProj.Models.BusinessEntities.Order", b => {
                  b.HasIndex("Id1", "Id2", "SomeReference").IsUnique();
              });
          }
      }