2011-03-07 3 views
2

web.config가 아닌 사용자 지정 구성 파일에서 Entity Framework 4 연결 문자열을 검색하려면 어떻게해야합니까?대체 위치에서 Entity Framework 연결 문자열 가져 오기?

편집 : 기본 생성자 생성 코드를 삭제하고 부분 클래스에서 다시 생성하여 연결 문자열을 사용하는 것이 합리적입니까?

나는 연결 문자열을 포함하여 오버로드 된 메서드를 사용하여 EF 컨텍스트에 대한 모든 참조를 변경하지 않는 것이 좋습니다.

@BrokenGlass : 이것은 우리가 결국 무엇을 :

당신이 연결 문자열을 전달할 수 있습니다 DataContext에 대한 생성자 과부하있다
public partial class STARSEntities 
{ 
    private const string _connectionStringFormat = @"metadata=res://*/STARS.EntityModel.STARSModel.csdl|res://*/STARS.EntityModel.STARSModel.ssdl|res://*/STARS.EntityModel.STARSModel.msl;provider=System.Data.SqlClient;provider connection string='Data Source={0};MultipleActiveResultSets=True'"; 

    /// <summary> 
    /// Initializes a new STARSEntities object using the connection string found in the STARS.xml configuration file. 
    /// </summary> 
    /// <remarks> 
    /// If the STARSEntities class is regenerated from the database, the default constructor needs to be removed from the generated file. 
    /// </remarks> 
    public STARSEntities() : base(GetConnectionString(), "STARSEntities") 
    { 
     this.ContextOptions.LazyLoadingEnabled = true; 
     OnContextCreated(); 
    } 

    private static string GetConnectionString() 
    { 
     return string.Format(_connectionStringFormat, ApplicationConfiguration.GetConnectionString("STARS")); 
    } 

} 
+0

무엇 EF를 컨텍스트 생성자를 사용하고 있습니까? 구성을 어떻게 든 전달해야합니다. 피할 수는 없습니다. – BrokenGlass

+0

지금은 web.config에서 연결 문자열을 참조하는 기본 생성자를 사용하고 있습니다. – Noel

답변

3

- 당신은 당신이 좋아하는 어디에서 설정을 할 수있는 경우가. 업데이트 된 질문에 따라

편집 :

정말 으로 연결 문자열을 포함하는 오버로드 된 메서드를 EF 컨텍스트 모든 참조를 변경하는 것을 방지하고 싶습니다.

문제는 T4 스크립트에 의해 생성 된 엔티티 컨텍스트 당신이 부분 클래스의 기본 생성자를 오버라이드 (override) 할 수 없기 때문에 연결 문자열

public const string ConnectionString = "name=FooEntities"; 

    public FooEntities() 
     : base(ConnectionString, ContainerName) 
    { 
     this.ContextOptions.LazyLoadingEnabled = true; 
    } 

로 사용되는 CONST 속성을 생성하는 당신의 유일한 옵션은 T4 스크립트 자체를 변경하는 것입니다 - 당신은 당신의 .TT 스크립트 파일에 다음을 참조한다 : 생성자 CA를 수정할 수 있습니다 사용할 수

public <#=code.Escape(container)#>() 
     : base(ConnectionString, ContainerName) 
    { 
<# 
     WriteLazyLoadingEnabled(container); 
#> 
    } 

이 연결 문자열을 강제하기를

public <#=code.Escape(container)#>() 
     : base(GetCustomConnectionString(), ContainerName) 
    { 
<# 
     WriteLazyLoadingEnabled(container); 
#> 
    } 

지금 GetCustomConnectionString() 별도로 당신이 볼

public partial class FooEntities : ObjectContext 
{ 
    public static string GetCustomConnectionString() 
    { 
    return "Foobar"; //however you want to determine connection string here 
    } 
} 

을 정의 할 수 있습니다 : LL은 별도의 파일에 (하지만 같은 부분 클래스 FooEntities에 대한) 정의 정적 메서드를 호출하여 연결 문자열을 결정하는 이것은 매우 복잡하고 깨지기 쉽기 때문에 이것을 권하지는 않을 것입니다.하지만 그렇게 할 수는 있습니다.

+0

이 방법을 직접 사용하지는 않았지만 정상적으로 작동합니다. 나는 게으르며 도메인 서비스가 엔티티 모델로부터 연결 문자열을 얻는 방법을 망쳐 놓고 싶지 않으므로 외부 생성자를 참조한 연결 문자열을 사용하도록 기본 EF 생성자를 다시 작성했습니다. – Noel

+0

@Noel : 방금 답변을 업데이트했습니다. 복잡하지만 가능한 작업 인 것 같습니다. T4 스크립트를 실행하여 자격을 다시 생성 할 때 변경된 생성자 호출이 재정의됩니다. 그러면 수동으로 * 매번 엔티티를 업데이트하십시오. – BrokenGlass

0

이 사용자 지정 구성 파일에서 연결 문자열을 읽을 수 있습니까? 그렇다면 ConnectionString을 사용하는 constructor for your DataContext을 사용할 수 있습니다.

NorthWindDataContext nwdc = new NorthWindDataContext(alternateConnectionString); 
0

아마도 이와 비슷한가요?

// replace the following line with any business logic you need to get to the file 
// with your connection string. If it is a config-style file, you can use the 
// Frameworks's helper classes as well 
string connectionString= File.ReadAllText("alternative path"); 
Entities ent = new Entity(connectionString); 

여기에 설명되어있는 내용은 post on Microsoft Connect입니다.이 당신을 위해 무엇을 물어 경우

2

은 몰라,하지만 당신은 connectionStrings 요소의 "configSource"속성을 사용할 수 있습니다

<connectionStrings configSource="connection.config"> 
</connectionStrings> 
+0

그것은 나를 위해 작동합니다. app.config가있는 EF 6. –

0

당신은 EntityConnectionStringBuilder를 사용할 수 있습니다

var ecb = new EntityConnectionStringBuilder(); 
ecb.Metadata = "res://*/Model.MyModel.csdl|res://*/Model.MyModel.ssdl|res://*/Model.MyModel.msl"; 
ecb.Provider = "System.Data.SqlClient"; 
ecb.ProviderConnectionString = connectionStringFromFancySource; 
return new MyModel(ecb.ToString()); 
관련 문제