2014-03-03 60 views
1

我想在运行时EF6设置一个连接字符串,使用VB.NET设置动态连接字符串EF6

部分实体类 - 这样我就可以在连接字符串传递。

Partial Public Class MyEntities 
    Public Sub New(connectionString As String) 
     MyBase.New(connectionString) 
    End Sub 
End Class 

代码调用类的错误了

Dim entityConnectionStringBuilder = New EntityConnectionStringBuilder() 

    entityConnectionStringBuilder.Provider = "System.Data.SqlClient" 
    entityConnectionStringBuilder.ProviderConnectionString = "Server=myServer;Database=myDatabase;User Id=myUserId;Password=myPassword;" 
    entityConnectionStringBuilder.Metadata = "res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl" 
    Using dbContext = New MyEntities(entityConnectionStringBuilder.ToString()) 
     Dim staffList = (From s In dbContext.Staffs).ToList 

     For Each staff1 In staffList 
      Console.WriteLine(String.Format("Staff {0}", staff1.username)) 
     Next 

    End Using 

例外:

System.Data.Entity.Core.MetadataException was unhandled 
    HResult=-2146232007 
    Message=Schema specified is not valid. Errors: 
MyModel.ssdl(2,2) : error 0152: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. 
    Source=EntityFramework 
    StackTrace: 
     at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.ThrowOnNonWarningErrors() 
     at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader.LoadItems(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths) 
     at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Loader..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, Boolean throwOnError, IDbDependencyResolver resolver) 
     at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection.Init(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths, Boolean throwOnError, IDbDependencyResolver resolver, DbProviderManifest& providerManifest, DbProviderFactory& providerFactory, String& providerInvariantName, String& providerManifestToken, Memoizer`2& cachedCTypeFunction) 
     at System.Data.Entity.Core.Metadata.Edm.StoreItemCollection..ctor(IEnumerable`1 xmlReaders, IEnumerable`1 filePaths) 
     at System.Data.Entity.Core.Metadata.Edm.MetadataCache.LoadStoreCollection(EdmItemCollection edmItemCollection, MetadataArtifactLoader loader) 
     at System.Data.Entity.Core.Metadata.Edm.MetadataCache.<>c__DisplayClass5.<>c__DisplayClass7.<GetMetadataWorkspace>b__1() 
     at System.Lazy`1.CreateValue() 
     at System.Lazy`1.LazyInitValue() 
     at System.Data.Entity.Core.Metadata.Edm.MetadataCache.<>c__DisplayClass5.<>c__DisplayClass7.<GetMetadataWorkspace>b__4() 
     at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.LoadAndCheckItemCollection[T](Func`1 itemCollectionLoader) 
     at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.<>c__DisplayClass16.<.ctor>b__f() 
     at System.Lazy`1.CreateValue() 
     at System.Lazy`1.LazyInitValue() 
     at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace, Boolean required) 
     at System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace.GetItemCollection(DataSpace dataSpace) 
     at System.Data.Entity.Core.Objects.ObjectContext.InitializeMappingViewCacheFactory(DbContext owner) 
     at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory) 
     at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection) 
     at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel() 
     at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel() 
     at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() 
     at System.Data.Entity.Internal.InternalContext.Initialize() 
     at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) 
     at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() 
     at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() 
     at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() 
     at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector) 
     at WpfTestDalEF6.MainWindow.Button_Click(Object sender, RoutedEventArgs e) in c:\users\arkle\documents\visual studio 2013\Projects\WpfTestDalEF6\WpfTestDalEF6\MainWindow.xaml.vb:line 14 
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
     at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) 
     at System.Windows.Controls.Button.OnClick() 
     at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e) 
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
     at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent) 
     at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target) 
     at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised) 
     at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args) 
     at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) 
     at System.Windows.Input.InputManager.ProcessStagingArea() 
     at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport) 
     at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel) 
     at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
     at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
     at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
     at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 
     at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 
     at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) 
     at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 
     at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 
     at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 
     at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 
     at System.Windows.Application.RunInternal(Window window) 
     at System.Windows.Application.Run() 
     at WpfTestDalEF6.Application.Main() in c:\users\arkle\documents\visual studio 2013\Projects\WpfTestDalEF6\WpfTestDalEF6\obj\Debug\Application.g.vb:line 65 
     at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
     at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
     at System.Threading.ThreadHelper.ThreadStart() 
    InnerException: 

什么我做错了任何想法?

+0

请看[这里](http://stackoverflow.com/questions/18455747/no-entity-framework-provider-found-for-the:这可以通过运行从Package Manager Console下面的命令来完成-ado-net-provider-with-invariant-name)并查看是否有帮助。 –

+0

我个人比较喜欢我在App.config中的连接字符串 – meda

+0

连接字符串是事先不知道的,这是应用程序的一个要求,例如,用户可以输入服务器等... – DermFrench

回答

1

尝试重新安装EntityFramework NuGet包,看看它是否适合你。

Install-Package EntityFramework