Вася Пупкин Вася Пупкин - 1 year ago 138
C# Question

Repositories in .net core library

I'm trying to wrap basic actions fro model(like get by id, etc.) in repositories. However I'm facing with two problems:

1. Connection String : Is there any solution to put it in config, and not to hard code it in class, like I did?

public const string ConnectionString = "Server = (localdb)\\mssqllocaldb;Database=pinchdb;Trusted_Connection=True;MultipleActiveResultSets=true";// can I get rid of it?
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Project> Projects { get; set; }
public DbSet<ProjectDepartments> ProjectsDepartments { get; set; }
public DbSet<Roles> Roles { get; set; }
public effMercContext(DbContextOptions<effMercContext> options)
: base(options)
protected override void OnModelCreating(ModelBuilder modelBuilder)
.HasKey(t => new { t.ProjectId, t.DepartmentId });
.HasOne(pt => pt.Project)
.WithMany(p => p.ProjectDepartment)
.HasForeignKey(pt => pt.ProjectId);
.HasOne(pt => pt.Department)
.WithMany(t => t.ProjectDepartment)
.HasForeignKey(pt => pt.DepartmentId);
public class EffMercDbContextFactory : IDbContextFactory<effMercContext>
public effMercContext Create(DbContextFactoryOptions options)
var builder = new DbContextOptionsBuilder<effMercContext>();
return new effMercContext(builder.Options);

2. Can I call Dbcontext without options to implement methods?

public Employee GetByID(int id)
var optionsBuilder = new DbContextOptionsBuilder<effMercContext>();// how can I get rid of this and just call effMercContext
using (effMercContext db = new effMercContext(optionsBuilder.Options))
return db.Employees.Where(x => x.Id == id).FirstOrDefault();

Answer Source
  1. You can put your connectionstring in appsettings.json as shown below. enter image description here Also, you can have config transforms for the appsettings.json based on the environments.

    in the Startup.cs

    enter image description here

    Access the above config while creating the DbContext.

            options =>
                    configuration["Data:DefaultConnection:ConnectionString"], b =>
    1. Add a default constructor to effMercContext. Then you shouldn't need to pass DbContextOptions.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download