에서 DbContext Connection String을 구현하려면 어떻게 해야 합니까?NET Core?
제 상황은 이 링크와 비슷하거나 적어도 제 코드는 비슷하고 에서 이와 같은 방법을 적용할 방법을 찾고 있습니다.NET Core 구문.
저의 구체적인 코드는 다음과 같습니다.
public partial class CompanyFormsContext : DbContext
{
public CompanyFormsContext()
: base("name=CompanyFormsContext")
{
}
public CompanyFormsContext(string connName)
: base("name=" + connName)
{
}
...
}
다음과 같은 오류가 발생합니다.
오류 CS1503 인수 1: 'string'에서 'Microsoft'로 변환할 수 없습니다.엔티티 프레임워크 코어.DbContextOptions의 회사 양식..NETCoreApp, 버전=v1.0
의 해 볼 때.base("name=CompanyFormsContext")
아니면base("name=" = connName)
.
에서 이 기능을 구현하는 올바른 방법은 무엇입니까?NET Core?
편집:
appsets.json 파일에 데이터베이스 연결을 위한 다음 정보가 있다는 것을 공유하고 싶었습니다. (그러나 startup.cs 에는 설정이 없습니다.)
"Data": {
"CompanyFormsContext": {
"ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
},
"CompanyFormsContextQA": {
"ConnectionString": "Server=(localdb)\\projectsv13;Database=companyforms;Trusted_Connection=True;"
}
}
그리고 저는 웹사이트에 데이터스토어를 등록하지 않는 Startup.cs 의 Adding DbContextOptions라는 링크를 발견했습니다. 그리고 저는 단순한 것인지 궁금합니다.protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
내 연결을 고치기에 충분할까요?
링크에서:
services.AddEntityFramework(Configuration)
.AddSqlServer()
.AddDbContext<MyDbContext>(
options =>
options.UseSqlServer(Configuration.Get("Data:CompanyFormsContext:ConnectionString"))
);
제 Startup.cs 에 이런 서비스가 필요합니까?
또 다른 옵션은 DbContextOptions를 취하는 기본 생성자를 호출하는 것입니다.
public BooksContext(string connectionString) : base(GetOptions(connectionString))
{
}
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
일반적으로 시작할 때 config에서 읽은 다음 연결 문자열을 사용하여 Entity Framework DbContext 서비스를 프로세스에 맞게 구성합니다.
1) 앱 설정에 줄을 추가합니다.json:
"DbConnectionString": "Server=s;Database=db;Trusted_Connection=True;",
2) Startup.cs 클래스의 행(Startup 메서드를 호출하여 Configuration(구성)을 작성한 후에는 일반적으로 ConfigureServices 메서드에서)을 읽어 보십시오.
var connection = Configuration["DbConnectionString"];
3) Entity Framework를 사용하는 경우 데이터베이스 컨텍스트 서비스를 추가합니다(MyDbContext는 EF에서 생성된 컨텍스트 클래스입니다).또한 기본 제공 종속성 주입을 통해 데이터베이스 컨텍스트를 인스턴스화하는 방법을 알려주어야 합니다.
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connection));
services.AddScoped<IMyDbContext, MyDbContext>();
여기서 IMyDbContext는 단순화되어 MyDbContext에서 추출한 인터페이스에 불과합니다.
4) 이제 MyDbContext를 취하도록 컨트롤러를 정의할 수 있으며 컨트롤러가 호출되면 DI가 해당 컨트롤러를 빌드하고 전달하는 작업을 수행합니다.
public MyController(IMyDbContext context)
{
_context = context // store for later use
}
IMO 모범 사례:
구성에 추가합니다.json:
"ConnectionStrings": {
"BooksContext": "Server=MyServer;Database=MyDb;Trusted_Connection=True;"
}
섹션을 초기화하는 방법:
services.AddDbContext<BooksContext>(options => options.UseSqlServer(configuration.GetConnectionString(nameof(BooksContext))));
쉬운 방법은 옵션 빌더를 사용하여 컨텍스트를 얻는 것입니다.
public static MyDbContext GetMyDbContext(string databaseName)
{
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseSqlServer($@"Data Source=.\SqlExpress;Initial Catalog={databaseName};Integrated Security=True");
return new MyDbContext(optionsBuilder.Options);
}
정적 연결을 위한 Startup.cs
services.AddScoped<MyContext>(_ => new MyContext(Configuration.GetConnectionString("myDB")));
동적 연결을 위한 Table1Repository.cs
using (var _context = new MyContext(@"server=....){
context.Table1....
}
MyContext.cs
public MyContext(string connectionString) : base(GetOptions(connectionString))
{
}
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
그래서 저는 연결할 시간까지 없는 데이터를 기반으로 데이터베이스에 동적으로 연결해야 하는 제 문제에 대한 해결책을 찾기 위해 여기저기를 찾았습니다.기본적으로, 역동적인 맥락입니다.URL에 전달되는 데이터가 없었고, 첨부할 수 있는 데이터베이스의 짧은 목록도 없었습니다.자, 여기 제기된 문제에 대한 제 해결책이 있습니다.이 코드를 사용하면 appsettings.json 파일을 사용하여 실행 시 코드로 대체할 자리 표시자와 연결 문자열을 정의할 수 있습니다.이 작업은 컨트롤러 또는 적합한 다른 클래스 내에서 수행할 수 있습니다.
정적 컨텍스트와 동적 컨텍스트를 모두 사용하고 있지만 동적 컨텍스트만 사용할 수 있습니다.
누군가가 이 일을 우연히 발견하고 감사의 말을 하기를 바랍니다.아마 누군가가 말할 것 같지만, 이 남자는 미쳤습니다.어느 쪽이든 즐기세요.
using System;
using System.Globalization;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace CallCenter.Repositories
{
public class TestRepository : ITestRepository
{
private readonly InsuranceContext _context;
public TestRepository(InsuranceContext context)
{
_context = context;
}
public void Add(string passedInStringWhichTellsWhatDatabaseToUse)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
var configuration = builder.Build();
var connectionString = configuration.GetConnectionString("DefaultConnection");
var agencyContext = new AgencyContext(connectionString.Replace("Database=replacethisstring", "Database=" + passedInStringWhichTellsWhatDatabaseToUse));
var company = agencyContext.Companys.FirstOrDefault(x => x.ColumnNameInDb == "xyz");
if (company != null)
{
companyId = company.CompanyId.ToString();
}
... your other code here which could include the using the passed in _context from the injected code (or you could not have any context passed in and just use dynamic context
}
}
}
}
//The AgencyContext class would look like this:
using Microsoft.EntityFrameworkCore;
namespace CallCenter.Entities
{
public class AgencyContext : DbContext
{
public AgencyContext(string connectionString) : base(GetOptions(connectionString))
{
}
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
public DbSet<Companys> Companys { get; set; }
}
}
//The startup.c IServiceProvider module has this:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddDbContext<InsuranceContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.UseRowNumberForPaging()));
services.AddScoped<ITestRepository , TestRepository >();
....
}
그리고 마지막으로 appsettings.jason 파일에 이 내용이 포함됩니다.
{
"ConnectionStrings": {
"DefaultConnection": "Server=yourservername;Database=replacethisstring;User ID=youruserid;Password=yourpassword;TrustServerCertificate=True;Trusted_Connection=False;Connection Timeout=30;Integrated Security=False;Persist Security Info=False;Encrypt=True;MultipleActiveResultSets=True;",
}
}
단순한 코드가 없는 솔루션을 찾고 있는 경우에는 기본 클래스에 대한 매개 변수로 정적 팩토리 메서드 호출이 있는 다른 생성자를 추가하면 됩니다.
public YourDbContext(string connectionString)
: base(new DbContextOptionsBuilder().UseSqlServer(connectionString).Options)
{
}
appsettings.json 파일에 연결 문자열이 있을 경우 허용되는 답변은 좋지만 멀티 테넌트 시스템과 같이 동적으로 연결 문자열을 구축해야 하는 경우도 있습니다.각 테넌트에 자체 데이터베이스가 있는 경우
이러한 종류의 시스템에서 연결 문자열의 저장 위치는 시간이 지남에 따라 변경될 수 있습니다. 예를 들어 초기에는 DB, 구성 파일, 나중에 보다 안전한 저장소로 이동할 수 있습니다.
이 경우 다음 단계를 수행할 수 있습니다.
- 1 - )(:IConnectionStringBuilder
그런 다음 연결 문자열 작성기가 를 구현합니다.
public interface IConnectionStringBuilder
{
string TenantConnectionString(string tenantIdentifier);
}
public class ConnectionStringBuilder : IConnectionStringBuilder
{
private readonly DbConnectionStringsConfig _stringsConfig;
public ConnectionStringBuilder(DbConnectionStringsConfig stringsConfig)
{
_stringsConfig = stringsConfig;
}
public string TenantConnectionString(string tenantIdentifier)
{
return @$"Server={_stringsConfig.Server};Database={_stringsConfig.Database};Trusted_Connection=True;MultipleActiveResultSets=true;Encrypt=False;";
}
}
- 2 - DbConnectionStringsConfig
입니다의 appsettings.json config를에 입니다.
"DbConnectionStringsConfig": {
"Server": "localhost",
"Database": "MyDB",
"UserId": "DEV_USER",
"Password": "DEV_PASWORD",
}
3 - Startup 또는 Program.cs 에서 새 클래스를 설정합니다.
services.AddSingleton<DbConnectionStringsConfig>(configuration.GetSection(nameof(DbConnectionStringsConfig)).Get<DbConnectionStringsConfig>());
그리고 나서.
services.AddTransient<IConnectionStringBuilder, ConnectionStringBuilder>();
4 - 그런 다음 DbContext를 구성하려면 다음 작업을 수행합니다.
services.AddDbContext<TenantDbContext>((s, o) =>
{
var connectionStringBuilder = s.GetService<IConnectionStringBuilder>();
// read the current tenant from HttpHeader in ITenantContext
var tenant = s.GetService<ITenantContext>()?.Tenant;
// build the connectionString for the current Tenant
var connectionString = connectionStringBuilder.TenantConnectionString(tenant?.Identifier)
?? DbConstants.DEV_DEFAULT_TENANT_CONNECTION_STRING;
o.UseSqlServer(connectionString, builder => builder.MigrationsAssembly(typeof(TenantDbContext).Assembly.FullName));
});
이 으로 ConnectionStrings 입니다 된다는 입니다.IConnectionStringBuilder
종류를 바꿔서 이런 식으로.
public class SuperSecretConnectionStringBuilder : IConnectionStringBuilder
{
...
}
services.AddTransient<IConnectionStringBuilder, SuperSecretConnectionStringBuilder>();
환경에 따라 다양한 유형의 ConnectionStringBuilders를 가질 수도 있으므로 DEV, STAGE 및 QA의 경우appsettings.config
파일, PROD의 경우 다른 것을 사용합니다.
언급URL : https://stackoverflow.com/questions/38878140/how-can-i-implement-dbcontext-connection-string-in-net-core
'programing' 카테고리의 다른 글
워드프레스 관리 페이지에서 사용자 정의 열 정렬 (0) | 2023.10.03 |
---|---|
mariadb : ODBCConf.exe로 ODBC 구성 (0) | 2023.10.03 |
sqalchemy의 선언적 ORM 확장자를 사용하는 경우 다중 열 인덱스 (0) | 2023.10.03 |
워드프레스:여러 언어를 선택할 경우 method="post" 사용 (0) | 2023.10.03 |
워드프레스 멀티사이트에서 사용자가 자신의 플러그인을 설치할 수 있도록 하려면 어떻게 해야 합니까? (0) | 2023.09.28 |