코드 우선 DbContext에 연결 문자열 전달
엔터티 프레임 워크의 코드 우선 DbContext에 연결 문자열을 어떻게 전달합니까? 내 데이터베이스 생성은 web.config의 DbContext와 연결 문자열이 동일한 프로젝트에 있고 이름이 같은 경우 올바르게 작동합니다. 하지만 이제 DbContext를 다른 프로젝트로 이동해야하므로 다음과 같이 연결 문자열을 테스트하고 있습니다.
모델 및 컨텍스트
public class Dinner
{
public int DinnerId { get; set; }
public string Title { get; set; }
}
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
: base(connString)
{
}
public DbSet<Dinner> Dinners { get; set; }
}
동작
public ActionResult Index()
{
var db = new NerdDinners(ConfigurationManager.ConnectionStrings["NerdDinnerDb"].ConnectionString);
var dinners = (from d in db.Dinners
select d).ToList();
return View(dinners);
}
Web.Config
<connectionStrings>
<add name="NerdDinnerDb" connectionString="Data Source=|DataDirectory|NerdDinners.sdf" providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
분석 작업에 중단 점을 설정 db
하면 연결 문자열이 있지만 데이터베이스 또는 아무것도 생성하거나 찾지 않습니다.
SQL Server에 대한 연결을 설정하는 동안 네트워크 관련 또는 인스턴스 관련 오류가 발생했습니다. 서버를 찾을 수 없거나 액세스 할 수 없습니다. 인스턴스 이름이 올 바르고 SQL Server가 원격 연결을 허용하도록 구성되어 있는지 확인하십시오. (공급자 : 명명 된 파이프 공급자, 오류 : 40-SQL Server에 대한 연결을 열 수 없음)
게임에 조금 늦었지만 또 다른 옵션은 다음과 같습니다.
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
{
this.Database.Connection.ConnectionString = connString;
}
public DbSet<Dinner> Dinners { get; set; }
}
문서를 읽은 후 대신 연결 문자열의 이름을 전달해야합니다.
var db = new NerdDinners("NerdDinnerDb");
"DbContext에 연결 문자열을 전달하는 방법"을 찾는 사람들을 위해이 비트를 추가 할 것이라고 생각했습니다. 기본 데이터 저장소에 대한 연결 문자열을 생성하고 전체 연결 문자열을 DbContext에서 파생 된 유형의 생성자에 전달할 수 있습니다. .
(@Lol Coder의 코드 재사용) 모델 및 컨텍스트
public class Dinner
{
public int DinnerId { get; set; }
public string Title { get; set; }
}
public class NerdDinners : DbContext
{
public NerdDinners(string connString)
: base(connString)
{
}
public DbSet<Dinner> Dinners { get; set; }
}
Then, say you construct a Sql Connection string using the SqlConnectioStringBuilder like so:
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(GetConnectionString());
Where the GetConnectionString method constructs the appropriate connection string and the SqlConnectionStringBuilder ensures the connection string is syntactically correct; you may then instantiate your db conetxt like so:
var myContext = new NerdDinners(builder.ToString());
In your DbContext, create a default constructor for your DbContext and inherit the base like this:
public myDbContext()
: base("MyConnectionString") // connectionstring name define in your web.config
{
}
If you are constructing the connection string within the app then you would use your command of connString. If you are using a connection string in the web config. Then you use the "name" of that string.
I have a little solution example for that problem.
MyDBContext.cs
public MyDBContext(DBConnectionType ConnectionType) //: base("ConnMain")
{
if(ConnectionType==DBConnectionType.MainConnection)
{
this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnMain"].ConnectionString;
}
else if(ConnectionType==DBConnectionType.BackupConnection)
{
this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnBackup"].ConnectionString;
}
}
MyClass.cs
public enum DBConnectionType
{
MainConnection=0,
BackupConnection=1
}
frmMyForm.cs
MyDBContext db = new MyDBContext(DBConnectionType.MainConnection);
//or
//MyDBContext db = new MyDBContext(DBConnectionType.BackupConnection);
Check the syntax of your connection string in the web.config. It should be something like ConnectionString="Data Source=C:\DataDictionary\NerdDinner.sdf"
When using an EF model, I have a connection string in each project that consumes the EF model. For example, I have an EF EDMX model in a separate class library. I have one connection string in my web (mvc) project so that it can access the EF db.
I also have another unit test project for testing the repositories. In order for the repositories to access the EF db, the test project's app.config file has the same connection string.
DB connections should be configured, not coded, IMO.
Can't see anything wrong with your code, I use SqlExpress and it works fine when I use a connection string in the constructor.
You have created an App_Data folder in your project, haven't you?
참고URL : https://stackoverflow.com/questions/4805094/pass-connection-string-to-code-first-dbcontext
'developer tip' 카테고리의 다른 글
각도 2에서 다시로드하지 않고 경로 매개 변수 변경 (0) | 2020.09.18 |
---|---|
Java 비교 두 목록 (0) | 2020.09.18 |
데이터베이스 / 모델에서 개체를 제거 할 때 Django 관리자가 파일을 삭제하도록하려면 어떻게해야합니까? (0) | 2020.09.18 |
git은 대소 문자를 구분하지 않습니까? (0) | 2020.09.18 |
tr 요소 주변의 테두리가 표시되지 않습니까? (0) | 2020.09.18 |