How to have multiple tables with the same schema in Entity Framework?

.net c# entity-framework entity-framework-6 sql-server

Question

I'm trying to have multiple tables with the same schema, within the same database, using Entity Framework.

For example, if I have the classes below, and I login to the SQL Server database, I can only see a table that is named something like dbo.Schema.

Is there a way to have multiple tables with the same schema?

class Context1 : DbContext
{
    public DbSet<Schema> table1 { get; set; }
}

class Context2 : DbContext
{
    public DbSet<Schema> table2 { get; set; }
}

class Schema
{
    [Key]
    public int EntryId { get; set; }
}
1
0
6/29/2018 6:56:53 PM

Popular Answer

Is there a way to have multiple tables with the same schema?

You can either use Data Annotations or Fluent API to configure the table and schema name.

Suppose you have the following model:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Using Data Annotations, you could name it blogging.blogs:

[Table("blogs", Schema = "blogging")]
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

Using Fluent API, you can override OnModelCreating method to name it blogging.blogs:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .ToTable("blogs", schema: "blogging");
    }
}
0
6/29/2018 7:38:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow