Вася Пупкин Вася Пупкин - 1 month ago 22
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)
{
modelBuilder.Entity<ProjectDepartments>()
.HasKey(t => new { t.ProjectId, t.DepartmentId });
modelBuilder.Entity<ProjectDepartments>()
.HasOne(pt => pt.Project)
.WithMany(p => p.ProjectDepartment)
.HasForeignKey(pt => pt.ProjectId);
modelBuilder.Entity<ProjectDepartments>()
.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>();
builder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=pinchdb;Trusted_Connection=True;MultipleActiveResultSets=true");
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
optionsBuilder.UseSqlServer(effMercContext.ConnectionString);
using (effMercContext db = new effMercContext(optionsBuilder.Options))
{
return db.Employees.Where(x => x.Id == id).FirstOrDefault();
}
}

Answer
  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.

          services.AddDbContext<ApplicationDbContext>(
            options =>
                options.UseSqlServer(
                    configuration["Data:DefaultConnection:ConnectionString"], b =>
                            b.MigrationsAssembly("MyProj.Web"))
    
    1. Add a default constructor to effMercContext. Then you shouldn't need to pass DbContextOptions.