Saturday, 4 May 2024

Entity Framework Core : Including Excluding Entities, Views, Table Valued Function in the DataModel.

We can include or exclude entity from DataModel using DBSet or OnModelCreating method like:

internal class MyContext : DbContext {

    public DbSet<Blog> Blogs { get; set; }  // Adding via DbSet

    protected override void OnModelCreating(ModelBuilder modelBuilder)  {

        modelBuilder.Entity<AuditEntry>(); // Adding via OnModelCreating; use either way.

    }

}

Note: Entities will be automatically added if declared in Navigation property.


Excluding Entity from Model:

[NotMapped]

public class BlogMetadata {

    public DateTime LoadedFromDatabase { get; set; }

}

or 

protected override void OnModelCreating(ModelBuilder modelBuilder) {

    modelBuilder.Ignore<BlogMetadata>();

}

Excluding Entity from Migration:

protected override void OnModelCreating(ModelBuilder modelBuilder) {

    modelBuilder.Entity<IdentityUser>()

        .ToTable("AspNetUsers", t => t.ExcludeFromMigrations());

}

Mapping Table Name explicitly with Entity:

[Table("blogs")]

public class Blog {

    public int BlogId { get; set; }

    public string Url { get; set; }

}

or

protected override void OnModelCreating(ModelBuilder modelBuilder) {

    modelBuilder.Entity<Blog>()

        .ToTable("blogs");

}

we can also mention schema name in Attribute/fluent API, if needed.

Mapping View with Entity

modelBuilder.Entity<Blog>().ToView("blogsView", schema: "blogging");

NoteMapping to a view will remove the default table mapping, but the entity type can also be mapped to a table explicitly. In this case the query mapping will be used for queries and the table mapping will be used for updates.

Mapping Table Valued Function with Entity

modelBuilder.Entity<BlogWithMultiplePosts>().HasNoKey().ToFunction("BlogsWithMultiplePosts");

NoteIn order to map an entity to a table-valued function the function must be parameterless.



No comments:

Post a Comment

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...