programing

Code First에서 데이터베이스 이름을 지정하는 방법은 무엇입니까?

goodcopy 2021. 1. 19. 08:05
반응형

Code First에서 데이터베이스 이름을 지정하는 방법은 무엇입니까?


EF에게 데이터베이스의 이름과 위치를 지정하려면 어떻게해야합니까?

Web.Config에 연결 문자열이 없으면 로컬 SQLEXPRESS 서버에 연결하려고하지만 알려진 SQL Server에 연결하고 원하는 이름을 지정하려고합니다. 어떤 제안?


컨텍스트와 동일한 이름으로 app.config / web.config에 연결 문자열을 생성하면 EF가 해당 DB를 사용합니다.


EF에서 다른 연결 문자열 이름을 사용하는 방법

EF는 연결 문자열에 데이터베이스 이름을 사용합니다. EF에서 연결 문자열의 이름을 분리하려면 생성자에 연결 문자열을 제공해야합니다. 예:

public class DatabaseContext : DbContext
{
    public DatabaseContext() 
      : base(ApplicationParameters.ConnectionStringName)
    {
    }

    public DatabaseContext(string connectionStringName)
      : base(connectionStringName)
    {
    }

}

클래스 :

public class Context : DbContext
{
    //SET CONNECTION STRING NAME FOR DataBase Name :
    public Context() : base("YourConnectionName") { }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

web.config에서 :

<connectionStrings>  
    <add name="YourConnectionName" connectionString="Data Source=A-PC\SQLEXPRESS;
    Initial Catalog=MyDataBase; Integrated Security=True" 
    providerName="System.Data.SqlClient" />
</connectionStrings>  

고마워요 ferventcoder.
참조 => http://brandonclapp.com/connection-strings-with-entity-framework-5-code-first/


또는 DbContext 생성자에서 이름을 설정할 수 있습니다.


이미 언급했듯이 애플리케이션의 구성 파일 내에서 이름 ( "YourDBName"이라고 말하자 )으로 연결 문자열을 선언 한 다음이를 DbContext기본 생성자 호출에 전달할 수 있습니다 (완전한 답변을 제공하기 위해 답변에 추가하겠습니다- 이미 이것에 대한 훌륭한 답변).

또는 속성을 DbContext사용 하여 Extension 클래스 에서 프로그래밍 방식으로 설정할 수 있습니다 Database.Connection.ConnectionString. 예를 들면 :

App.config :

<!-- More.... -->
<!-- You can do this in a declarative way -->
<connectionStrings>
  <add name="YourDBName"
       connectionString="<Your connection string here>"
       providerName="<Your provider here>" />
</connectionStrings>
<!-- More.... -->

DatabaseContext.cs :

public class DatabaseContext : DbContext
    //Link it with your config file
    public DatabaseContext () : base("YourDBName") 
    {
        //And/Or you can do this programmatically.
        this.Database.Connection.ConnectionString = "<Your Connection String Here>";
        // More Stuff.....
    }
}

기존 데이터베이스에서 연결 문자열을 가리키면 EF "코드 우선"이 자동으로 생성하지 않습니다.

EF "코드 우선"은 기본적으로 컨텍스트 클래스가 컨텍스트 클래스와 이름이 같은 연결 문자열을 찾는 규칙을 사용합니다.

Using ef code first with an existing database


For reference, here is how to do it in code using VB.NET:

Public Class DatabaseContext : Inherits DbContext

Public Property Users As DbSet(Of User)

Public Sub New()
    MyBase.New("NewFileName.sdf")
End Sub

End Class

ReferenceURL : https://stackoverflow.com/questions/5346926/how-to-specify-database-name-in-code-first

반응형