2013-03-03 41 views
0

據我所知,連接字符串僅附加到一個類。但是如果我有很多Model類呢?我可以爲多個類使用一個連接字符串嗎?我可以有多個Model類的連接字符串嗎?

這是我UserModel.cs文件的簡單版本:

public class UserModel 
{ 
    public int Id { get; set; } 
    public string Email { get; set; } 
} 

public class UserTable : DbContext 
{  
    public UserModel GetByEmail(string Email) 
    {  
     return this.Database.SqlQuery<UserModel>("SELECT * FROM Users WHERE [email protected]", new SqlParameter("Email", Email)).SingleOrDefault();  
    } 
} 

這是連接字符串:

<connectionStrings> 
    <add name="UserModel" 
     connectionString="Server=.\SQLEXPRESS;Database=MyDatabase;User Id=MyUser;Password=MyPassword;" 
     providerName="System.Data.SqlClient" /> 
</connectionStrings> 

現在可以說,我想添加一個名爲DataTable中一個新的Model類也是從用戶表格中的DbContext派生而來的。我是否需要一個名稱相同的連接字符串,還是可以使用已定義的連接字符串?處理多個Model類和連接字符串的傳統方式是什麼?

回答

0

連接字符串定義連接到數據庫所需的參數。

也許我認爲你正在討論或混淆SQL查詢與connectionstring。

是的,一個SQL查詢可以在任何給定的時間查詢多個表。 也許你可以查看谷歌上的「SQL查詢語句」瞭解深度信息。

+0

沒有我說的關於連接字符串。對不起,但我看到它可能會混淆,現在編輯我原來的帖子。關鍵是我有兩個類,UserTable和DataTable,它們都是從DbContext派生的,它們共享一個連接字符串或者擁有它們。 – Espen 2013-03-03 12:27:29

+0

連接字符串通常用於標識,配置和連接到數據庫。 SQL查詢用於與表交互並詢問表。通常我只是將SQL查詢字符串自定義爲目標,而不是有一個函數可以完成所有操作(因爲某些用戶擁有和按照某些書中的建議)通常會像GetDbData(Tablename,ReqFields(),ReqValues()) 。因此,我將爲GetUserByEmail(電子郵件)提供一個函數,爲GetUserByTaxId(TaxId)提供另一個函數,爲GetUserByOccupation(JobTitle)提供另一個函數。這是我的方式,每個人都有自己的風格? – Zeddy 2013-03-03 12:41:40

+0

重要的是您驗證輸入的數據(如果有),以避免SQL注入攻擊。 – Zeddy 2013-03-03 12:43:33

1

DbContext類使用ConnectionString建立到數據庫的連接。

您通常會擁有由DbContext公開的多個模型類。

可能有多個DbContext對象使用相同的連接字符串值連接到數據庫。通過這種方式,如果需要(例如,如果您正在創建訪問不同表格但爲應用程序提供類似服務的單獨程序集),則可以將模型的各個部分分隔爲不同的上下文。

需要注意EF至少5.0的注意事項,不能使用多個DbContext的代碼優先的遷移,一個會覆蓋另一個的更改。解決此問題的方法是創建僅用於遷移過程的聚合DbContext。

我已經在我創建的應用程序中完成了這項工作。我使用Unity IoC容器,並且構建了一個允許我將ConnectionStringName傳遞到分離的DbContext中的插件接口。在組件中的一個插件的一個例子是:

public class Bootstrapper : IBootstrapper 
{ 
    public void Bootstrap(IUnityContainer container, string connectionStringName) 
    { 
     container.RegisterType<ISQService, SQService>(); 
     container.RegisterType<ISQEntities, SQEntities>(
      new HierarchicalLifetimeManager(), new InjectionConstructor(connectionStringName)); 
     container.RegisterType<IController, SQController>("SQ"); 
    } 
} 

我的Global.asax引用下面的引導程序類:

protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     ModelBinders.Binders[typeof(DataTable)] = new DataTableModelBinder(); 
     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 

     Bootstrapper.Initialise(); 
    } 

    protected void Application_End() 
    { 
     Bootstrapper.Dispose(); 
    } 

引導程序

public static class Bootstrapper 
{ 
    private static IUnityContainer container; 

    public static void Initialise() 
    { 
     container = BuildUnityContainer(); 
     DependencyResolver.SetResolver(new UnityDependencyResolver(container)); 
    } 

    public static void Dispose() 
    { 
     container.Dispose();     
    } 

    private static void RegisterPlugins(IUnityContainer theContainer, string wildcard, string connectionStringName) 
    { 
     var pluginBootStrappers = from Assembly assembly in wildcard.LoadAssemblies() 
            from type in assembly.GetExportedTypes() 
            where typeof(IBootstrapper).IsAssignableFrom(type) 
            select (IBootstrapper)Activator.CreateInstance(type); 

     pluginBootStrappers.ToList().ForEach(b => b.Bootstrap(theContainer, connectionStringName)); 
    } 

    private static IUnityContainer BuildUnityContainer() 
    { 
     var theContainer = new UnityContainer(); 
     const string ConnectionStringName = "MyDb"; 

     RegisterPlugins(theContainer, "MyApp.Systems.*.dll", ConnectionStringName); 

     // Register Application Specific objects 
     theContainer.RegisterType<IMyEntities, MyEntities>(
      new HierarchicalLifetimeManager(), 
      new InjectionConstructor(ConnectionStringName)); 

     theContainer.RegisterType<IAimaService, AimaService>(); 

     var factory = new UnityControllerFactory(theContainer); 
     ControllerBuilder.Current.SetControllerFactory(factory); 

     return theContainer; 
    } 
} 
相關問題