Kro*_*oss 4 .net-core asp.net-core aspnetboilerplate
我想从"数据"表中隔离"帐户"表,以便重用另一个应用程序.
我尝试使用.NET Core 2.0 + Angular模板,创建2个连接字符串,但是当创建另一个AbpDbContext时,我无法为上下文设置连接字符串.
在GitHub上使用多个DB上下文的示例使用.NET框架,而不是.NET核心,允许在dbcontext ctor上设置连接字符串.如何在.net core 2模板上执行此操作?
Rav*_*agi 15
在ASP.NET ZERO/ASP.NET BOILERPLATE中连接多个数据库.
注 - 使用单独的DB上下文来使用多个数据库.
步骤1.在表的"MultipleDbContextEfCoreDemo.Core"项目中创建模态类.
[Table ("tblStudent")] //Is in First Database
public class Student : Entity<long> {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
protected Student () { }
}
[Table ("tblCourses")] //Is in Second Database
public class Courses : Entity<long> {
public int ID { get; set; }
public string CourseName { get; set; }
public string Standard { get; set; }
protected Courses () { }
}
Run Code Online (Sandbox Code Playgroud)
步骤2.在同一项目("MultipleDbContextEfCoreDemo.Core"项目)中,创建/使用"MultipleDbContextEfCoreDemoConsts.cs"文件以添加数据库连接名称.
public class MultipleDbContextEfCoreDemoConsts
{
public const string LocalizationSourceName = "MultipleDbContextEfCoreDemo";
public const string ConnectionStringName = "Default";
public const string SecondDbConnectionStringName = "Second";
}
Run Code Online (Sandbox Code Playgroud)
步骤3.在"MultipleDbContextEfCoreDemo.EntityFrameworkCore"项目中转到"EntityFrameworkCore"文件夹并为要连接的每个数据库连接创建单独的"DBContext"和"DbContextConfigurer"文件.
FirstDatabase设置 -
连接到第一个db所需的文件 -
1. FirstDbContext.cs
public class FirstDbContext : AbpDbContext, IAbpPersistedGrantDbContext {
/* Define an IDbSet for each entity of the application */
public DbSet<PersistedGrantEntity> PersistedGrants { get; set; }
public virtual DbSet<Student> Student { get; set; }
public FirstDbContext (DbContextOptions<FirstDbContext> options) : base (options) {
}
protected override void OnModelCreating (ModelBuilder modelBuilder) { }
}
Run Code Online (Sandbox Code Playgroud)
2. FirstDbContextConfigurer
public static class FirstDbContextConfigurer {
public static void Configure (DbContextOptionsBuilder<FirstDbContext> builder, string connectionString) {
builder.UseSqlServer (connectionString);
}
public static void Configure (DbContextOptionsBuilder<FirstDbContext> builder, DbConnection connection) {
builder.UseSqlServer (connection);
}
}
Run Code Online (Sandbox Code Playgroud)
SecondDatabase设置 -
连接到第二个db所需的文件 -
1. SecondDbContext.cs
public class SecondDbContext : AbpDbContext, IAbpPersistedGrantDbContext {
/* Define an IDbSet for each entity of the application */
public DbSet<PersistedGrantEntity> PersistedGrants { get; set; }
public virtual DbSet<Student> Student { get; set; }
public SecondDbContext (DbContextOptions<SecondDbContext> options) : base (options) {
}
protected override void OnModelCreating (ModelBuilder modelBuilder) { }
}
Run Code Online (Sandbox Code Playgroud)
2. SecondDbContextConfigurer
public static class SecondDbContextConfigurer {
public static void Configure (DbContextOptionsBuilder<SecondDbContext> builder, string connectionString) {
builder.UseSqlServer (connectionString);
}
public static void Configure (DbContextOptionsBuilder<SecondDbContext> builder, DbConnection connection) {
builder.UseSqlServer (connection);
}
}
Run Code Online (Sandbox Code Playgroud)
步骤4.然后在同一个项目("MultipleDbContextEfCoreDemo.EntityFrameworkCore")中添加"MyConnectionStringResolver.cs"
public class MyConnectionStringResolver : DefaultConnectionStringResolver
{
public MyConnectionStringResolver(IAbpStartupConfiguration configuration)
: base(configuration)
{
}
public override string GetNameOrConnectionString(ConnectionStringResolveArgs args)
{
if (args["DbContextConcreteType"] as Type == typeof(SecondDbContext))
{
var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
return configuration.GetConnectionString(MultipleDbContextEfCoreDemoConsts.SecondDbConnectionStringName);
}
return base.GetNameOrConnectionString(args);
}
}
Run Code Online (Sandbox Code Playgroud)
步骤5.然后在同一个项目("MultipleDbContextEfCoreDemo.EntityFrameworkCore")中,更新"MultipleDbContextEfCoreDemoEntityFrameworkCoreModule.cs"文件,将"IConnectionStringResolver"替换为我们的自定义实现MyConnectionStringResolver.
[DependsOn(typeof(MultipleDbContextEfCoreDemoCoreModule), typeof(AbpEntityFrameworkCoreModule))]
public class MultipleDbContextEfCoreDemoEntityFrameworkCoreModule : AbpModule
{
public override void PreInitialize()
{
Configuration.ReplaceService<IConnectionStringResolver, MyConnectionStringResolver>();
// Configure first DbContext
Configuration.Modules.AbpEfCore().AddDbContext<FirstDbContext>(options =>
{
if (options.ExistingConnection != null)
{
FirstDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
FirstDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
// Configure second DbContext
Configuration.Modules.AbpEfCore().AddDbContext<SecondDbContext>(options =>
{
if (options.ExistingConnection != null)
{
SecondDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
}
else
{
SecondDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
}
});
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(MultipleDbContextEfCoreDemoEntityFrameworkCoreModule).GetAssembly());
}
}
Run Code Online (Sandbox Code Playgroud)
步骤6.使用Dto,Interface和Service Class在"MultipleDbContextEfCoreDemo.Application"项目中创建服务.
ITestAppService.cs-
public interface ITestAppService : IApplicationService
{
List<string> GetStudentAndCourses();
}
Run Code Online (Sandbox Code Playgroud)
TestAppService.cs
public class TestAppService : MultipleDbContextEfCoreDemoAppServiceBase, ITestAppService
{
private readonly IRepository<Student> _studentRepository; //in the first db
private readonly IRepository<Courses> _coursesRepository; //in the second db
public TestAppService(
IRepository<Student> studentRepository,
IRepository<Courses> coursesRepository
)
{
_studentRepository = studentRepository;
_coursesRepository = coursesRepository;
}
//a sample method uses both databases concurrently
public List<string> GetStudentAndCourses()
{
List<string> names = new List<string>();
var studentNames = _studentRepository.GetAllList().Select(p => "Student: " + p.FirstName).ToList();
names.AddRange(peopleNames);
var courseNames = _coursesRepository.GetAllList().Select(p => "Course: " + p.CourseName).ToList();
names.AddRange(courseNames);
return names;
}
}
Run Code Online (Sandbox Code Playgroud)
步骤7.将数据库connectionStrings添加到MultipleDbContextEfCoreDemo.Web/MultipleDbContextEfCoreDemo.Web.Host项目的"appsettings.json"文件中.
{
"ConnectionStrings": {
"Default":
"Server=XXX.XXX.XX.XX;Database=firstDB;Integrated Security=False;TrustServerCertificate=True;User ID=XX;Password=XXX;",
"Second":
"Server=XXX.XXX.XX.XX;Database=secondDB;Integrated Security=False;TrustServerCertificate=True;User ID=XX;Password=XXX;"
}
}
Run Code Online (Sandbox Code Playgroud)
步骤8.在angular/MVC项目中使用Service.
| 归档时间: |
|
| 查看次数: |
1568 次 |
| 最近记录: |