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;
}
}
沒有我說的關於連接字符串。對不起,但我看到它可能會混淆,現在編輯我原來的帖子。關鍵是我有兩個類,UserTable和DataTable,它們都是從DbContext派生的,它們共享一個連接字符串或者擁有它們。 – Espen 2013-03-03 12:27:29
連接字符串通常用於標識,配置和連接到數據庫。 SQL查詢用於與表交互並詢問表。通常我只是將SQL查詢字符串自定義爲目標,而不是有一個函數可以完成所有操作(因爲某些用戶擁有和按照某些書中的建議)通常會像GetDbData(Tablename,ReqFields(),ReqValues()) 。因此,我將爲GetUserByEmail(電子郵件)提供一個函數,爲GetUserByTaxId(TaxId)提供另一個函數,爲GetUserByOccupation(JobTitle)提供另一個函數。這是我的方式,每個人都有自己的風格? – Zeddy 2013-03-03 12:41:40
重要的是您驗證輸入的數據(如果有),以避免SQL注入攻擊。 – Zeddy 2013-03-03 12:43:33