Create View by Code First from EF Core 3.1

Viewed 316

I want to create sql view like a table at EF Core by Code First. How can I do this? Could you help me please?

1 Answers

This can help you

Entity:

public class Personel  
{
    public string Name { get; set; }
}

DBContext:

public DbSet<Personel> Personels { get; set; }

On Model Creating:

builder.Entity<Personel>(eb => {
    eb.HasNoKey();
    eb.ToView("View_Personel");
    eb.Property(v => v.Name).HasColumnName("Name");
});

Add-Migration

migrationBuilder.Sql("
    CREATE VIEW View_Personel AS
        SELECT MatchValue AS Name
        FROM Personel");

In addition, you can create with SQL Method Procedure, Materialized View, etc. by Code First (not DBFirst).

Related