2012-05-11 66 views
1

如何在我的web.config中共享我的DBcontext而不創建多個連接?MVC 3 - 數據庫上下文 - Web.Config

WEB.config: 
    <configuration> 
     <connectionStrings> 
     <add name="daC_Companies" connectionString="Data Source=10.0.2.100;Initial Catalog=XXXXX;User ID=XXXXXXXXXx;Password=XXXXXXXX;Persist Security Info=False" providerName="System.Data.SqlClient" /> 
     </connectionStrings> 


Data Access: 
     public class daC_Companies : DbContext 
     { 
      public DbSet<ClassLibrary.Companies.C_Companies> dbsetC_Companies { get; set; } 
     } 

然後我有一個名爲C_Companies的類引用上面。它工作正常,但我不想爲每個我想要訪問的類都創建一個新的DBContext。

回答

1

DbContext應該特定於數據庫而不是對象。要添加對更多分表的引用,請將它們作爲屬性添加到daC_Companies對象中:

public class daC_Companies : DbContext 
    { 
     public DbSet<ClassLibrary.Companies.C_Companies> dbsetC_Companies { get; set; } 
     public DbSet<ClassLibrary.Companies.Object2> Object2s { get; set; } 
     public DbSet<ClassLibrary.Companies.Object3> Object3s { get; set; } 
     public DbSet<ClassLibrary.Companies.Object4> Object4s { get; set; } 
    }