checai
checai

Reputation: 926

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

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; }
}

Upvotes: 0

Views: 4699

Answers (2)

kimbaudi
kimbaudi

Reputation: 15545

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");
    }
}

Upvotes: 1

Dharmeshsharma
Dharmeshsharma

Reputation: 691

You can simple do like this with multiple tables.

public partial class AdventureWorksEntities : DbContext
{
    public AdventureWorksEntities()
        : base("name=AdventureWorksEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Address> Addresses { get; set; }
    public virtual DbSet<AddressType> AddressTypes { get; set; }
    public virtual DbSet<Contact> Contacts { get; set; }
    public virtual DbSet<ContactType> ContactTypes { get; set; }
    public virtual DbSet<CountryRegion> CountryRegions { get; set; }
    public virtual DbSet<StateProvince> StateProvinces { get; set; }
}

in this code we can add more table from same database. There is no need to create another class and inherit DbContext. or you can do Add Item into project-> New Item->Data->ADO.NET Entity Data Model. This will generate same code with your selected tables.

Thanks

Upvotes: 0

Related Questions