2010-09-23 42 views
8

Tôi đang sử dụng Khung thực thể 4 trong dự án của tôi. Khung đã tạo ra chuỗi kết nối riêng của mình, vì vậy web.config connectionStrings phần tập tin của tôi trông như sau:Khung thực thể - chuỗi kết nối dự phòng

<connectionStrings> 
    <add name="ApplicationServices" connectionString="data source=localhost;user id=user;pwd=pass;initial catalog=VNK" providerName="System.Data.SqlClient" />  
    <add name="VNKEntities" connectionString="metadata=res://*/VNKModel.csdl|res://*/VNKModel.ssdl|res://*/VNKModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=localhost;Initial Catalog=VNK;User ID=user;Password=pass;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 

Chuỗi kết nối đầu tiên được gọi là ApplicationServices là một trong những ban đầu của tôi. Thứ hai, được gọi là VNKEntities đã được tạo trong khi tạo mô hình.

Khi tôi kiểm tra được tạo ra * .edmx tập tin, tôi thấy rằng mô hình này là tham khảo chuỗi kết nối của nó, được trình bày dưới đây:

/// <summary> 
    /// Initializes a new VNKEntities object using the connection string found in the 'VNKEntities' section of the application configuration file. 
    /// </summary> 
    public VNKEntities() : base("name=VNKEntities", "VNKEntities") 
    { 
     this.ContextOptions.LazyLoadingEnabled = true; 
     OnContextCreated(); 
    } 

Câu hỏi của tôi là làm thế nào tôi có thể thoát khỏi những VNKEntities chuỗi kết nối và chỉ để lại ApplicationServices, mà tôi sẽ tham chiếu từ mô hình của tôi? Tôi chỉ muốn có một chuỗi kết nối tới cơ sở dữ liệu, vì tôi chỉ sử dụng một cơ sở dữ liệu (thay thế tham số hàm tạo từ name=VNKEntities thành name=ApplicationServices không hoạt động).

Trân

Trả lời

3

Mặc dù bạn có thể tạo kết nối bằng mã, như @gandjustas chỉ ra (+1), bạn không thể thoát khỏi việc có chuỗi kết nối hoặc EntityConnection.

Điều này là do nó không thực sự dư thừa. Có, phần kết nối cơ sở dữ liệu là không cần thiết và @gandjustas chỉ cho bạn cách xóa bỏ dự phòng đó. Tuy nhiên, chuỗi kết nối khung thực thể cũng chứa thông tin về mô hình của bạn, không tìm thấy bất kỳ đâu trong chuỗi kết nối mà bạn muốn giữ lại. Thông tin mô hình này phải đến từ đâu đó. Bạn có phải loại bỏ chuỗi kết nối của khung thực thể và sử dụng hàm tạo danh sách tham số trên ObjectContext, bạn sẽ loại bỏ tất cả các tham chiếu đến mô hình.

+0

Cảm ơn bạn đã giải thích chi tiết, điều này đã giúp tôi hiểu tại sao tôi nên chọn giải pháp do @gandjustas đưa ra để giải quyết vấn đề của tôi. – jwaliszko

1

Tôi gặp vấn đề tương tự. Tôi đã giải quyết nó bằng cách làm theo cách sau:

Tôi đã tạo hai tệp edmx, nhưng khi tạo tệp edmx thứ hai, tôi bỏ qua chuỗi kết nối sẽ được lưu trong tệp cấu hình. Bằng cách này, tập tin cấu hình của tôi sẽ chỉ giữ một chuỗi kết nối. Sau đó, tôi biến đổi dòng sau trong chuỗi kết nối của tôi:

<add name="MyDbContext" connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider connection string=&quot;data source=abc;initial catalog=mydb;persist security info=True;user id=myuser;password=password;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 

Chỉ cần thay thế "res: //model1.csdl" với "res: // * /" và nó hoạt động như một nét duyên dáng.

Bạn có thể chỉ định tên kết nối này trong constructor của lớp dbcontext của bạn như:

public MyDbContext() : base("name=NameOfYourConnectionString") // Name of your connection string 
{ } 

Lưu ý: Tôi đang sử dụng Entity Framework 5.0.

1

Tôi sẽ cung cấp triển khai đầy đủ Tôi đã làm để giải quyết vấn đề này (dựa trên gợi ý của gandjustas). Tôi đã viết một wrapper đơn giản cho bối cảnh, có thể được sử dụng trong các cách sau đây:

using (var wrapper = new ContextWrapper<VNKEntities>()) 
{ 
    // do your stuff based on wrapper.Context 
} 

Loại ContextWrapper là một mẫu mà chỉ đơn giản kết thúc tốt đẹp bối cảnh mà chỉ được xây dựng theo một cách hơi khác (sử dụng chỉ có một chuỗi kết nối) và sau đó được hiển thị bởi thuộc tính. thực hiện nội bộ của mình được đặt bên dưới:

public class ContextWrapper<TContext> : IDisposable 
    where TContext : ObjectContext 
{ 
    private TContext _context; 
    private EntityConnectionManager _manager; 
    private bool _disposed; 

    public ContextWrapper() 
     : this(true) 
    { 
    } 

    public ContextWrapper(bool lazyLoadingEnabled) 
    { 
     _disposed = false; 
     _manager = new EntityConnectionManager(); 
     _context = (TContext)Activator.CreateInstance(typeof(TContext), _manager.Connection); 
     _context.ContextOptions.LazyLoadingEnabled = lazyLoadingEnabled; 
    } 

    ~ContextWrapper() 
    { 
     Dispose(false); 
    } 

    public TContext Context 
    { 
     get { return _context; } 
    } 

    public void Dispose() 
    { 
     Dispose(true); 
     GC.SuppressFinalize(this); 

    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (!_disposed) 
     { 
      if (disposing) 
      { 
       if (_manager != null) 
       { 
        _manager.Dispose(); 
        _manager = null; 
       } 
       var ctx = _context as IDisposable; 
       if (ctx != null) 
       { 
        ctx.Dispose(); 
        _context = null; 
       } 
      } 
     } 
     _disposed = true; 
    } 
} 

Bạn có thể thấy việc sử dụng lớp tùy chỉnh tên EntityConnectionManager:

internal class EntityConnectionManager : IDisposable 
{ 
    private DbConnection _connection; 
    private EntityConnection _entityConnection; 

    private volatile bool _disposed; 

    public EntityConnectionManager() 
    { 
     var workspace = new MetadataWorkspace(Setting.MetadataWorkspacePaths.Split('|'), new[] { Assembly.ReflectionOnlyLoad(Setting.MetadataAssemblyNameToConsider) }); 

     _connection = new SqlConnection(Setting.ConnectionString); 
     _entityConnection = new EntityConnection(workspace, _connection); 
     _disposed = false; 
    } 

    public EntityConnection Connection 
    { 
     get { return _entityConnection; } 
    } 

    public void Dispose() 
    { 
     Dispose(true); 
     GC.SuppressFinalize(this); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if (!_disposed) 
     { 
      if (disposing) 
      { 
       if (_connection != null) 
       { 
        _connection.Dispose(); 
        _connection = null; 
       } 
       if (_entityConnection != null) 
       { 
        _entityConnection.Dispose(); 
        _entityConnection = null; 
       } 
      } 
     } 
     _disposed = true; 
    } 
} 

Vì vậy, bây giờ bạn có thể có chuỗi một kết nối:

<connectionStrings> 
    <add name="ApplicationServices" connectionString="data source=localhost;user id=user;pwd=pass;initial catalog=VNK;Pooling=False;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />  
</connectionStrings> 

và siêu dữ liệu được xác định trong phần cài đặt ứng dụng (điểm chính thứ hai để lắp ráp nơi mô hình miền của bạn thực sự được lưu trữ):

<appSettings> 
    <add key="MetadataWorkspacePaths" value="res://*/VNKModel.csdl|res://*/VNKModel.ssdl|res://*/VNKModel.msl" /> 
    <add key="MetadataAssemblyNameToConsider" value="VNK.Models" /> 
</appSettings> 

Logic cho loại Setting rất đơn giản, vì nó chỉ kéo cài đặt từ tệp cấu hình.

Các vấn đề liên quan