.net 核心库中的存储库

Repositories in .net core library

我正在尝试将模型的基本操作(如通过 ID 获取等)包装在存储库中。但是我面临两个问题:

1. Connection String : 有什么解决方案可以把它放在配置中,而不是像我一样在 class 中硬编码吗?

 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。我可以在没有选项的情况下调用 Dbcontext 来实现方法吗?

      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();
        }
    }
  1. 您可以将连接字符串放入 appsettings.json 中,如下所示。 此外,您可以根据环境为 appsettings.json 使用 config transforms

    在Startup.cs

    在创建 DbContext 时访问上述配置。

          services.AddDbContext<ApplicationDbContext>(
            options =>
                options.UseSqlServer(
                    configuration["Data:DefaultConnection:ConnectionString"], b =>
                            b.MigrationsAssembly("MyProj.Web"))
    
    1. 将默认构造函数添加到 effMercContext。那么你不需要传递 DbContextOptions.