I would like to ask, if it is possible to target only one table with DbContext in Entity Framework Core?
In shortcut, I have a system that manages everything about database and all of the tables in it, but now I am writing new system, that uses the same database, but only needs one of the tables. Also I do not really need all the entities in method OnModelCreating
etc...
Lets say I have something like:
public virtual DbSet<Admin> Admins { get; set; }
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Project> Projects { get; set; }
public virtual DbSet<AdminProject> AdminProjects { get; set; }
public virtual DbSet<UserProject> UserProjects { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// something
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//modelBuilder for all of the tables
}
but I would prefer simply just:
public virtual DbSet<Project> Projects { get; set; }
and later in OnModelCreating
just model for Project entity.
Thank you for all your help
assuming that your new project uses a copy of the original DbContext
you can simply remove anything you don't need.
Unless you create a migration from the new context this won't change your database.
It might be worth mentioning: A code first approach, where the DB is generated based on your code, would typically be managed by a shared DbContext
since you can't have multiple __MigrationHistory
tables in a single Database.
You can use mapping. First create the model of the table you will use. Like
public class Foo
{
public string Id { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
After crate mapping class
public class FooMapping : IEntityTypeConfiguration<Foo>
{
public void Configure(EntityTypeBuilder<Foo> builder)
{
builder.ToTable("FooTable");
builder.Property(c => c.Id).HasColumnName("nameofyourcolumninsqltable").IsRequired();;
builder.Property(c => c.Name).HasColumnName("nameofyourcolumninsqltable");;
builder.Property(c => c.Phone).HasColumnName("nameofyourcolumninsqltable");
}
}
Finally initialize in the DbContex
public class Context : DbContext
{
public Context(DbContextOptions< Context > options) : base(options)
{
}
public Context()
{
}
public DbSet<Foo> Foos { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new FooMapping());
base.OnModelCreating(modelBuilder);
}
}