I have the following connection string that is used by a generated EF model. It works correctly on my local machine but when I deploy, I get the error below. I have look at the URL referenced many time on SO: http://blogs.teamb.com/craigstuntz/2010/08/13/38628/ and if it has the answer in it, I don't see it for my case.
I'm pasting the error below
<add name="svcodecampEntitiesAllTables" connectionString="metadata=res://*/EFModel.ModelAllTables.csdl|res://*/EFModel.ModelAllTables.ssdl|res://*/EFModel.ModelAllTables.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=svcc;integrated security=True;persist security info=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
{"message":"An error has occurred.","exceptionMessage":"Unable to load the specified metadata resource.","exceptionType":"System.Data.MetadataException","stackTrace":" at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)\r\n at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource..ctor(String originalPath, String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)\r\n at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)\r\n at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)\r\n at System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths)\r\n at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()\r\n at System.Data.Common.Utils.Memoizer`2.Result.GetValue()\r\n at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)\r\n at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)\r\n at System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()\r\n at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)\r\n at System.Data.Objects.ObjectContext..ctor(EntityConnection connection)\r\n at System.Data.Entity.Internal.InternalConnection.CreateObjectContextFromConnectionModel()\r\n at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()\r\n at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()\r\n at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()\r\n at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()\r\n at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)\r\n at WebAPI.rest.AttendeesDashboardController.Get(String userSearch, Nullable`1 presentersOnly, Nullable`1 currentCodeCampYearOnly, Nullable`1 start, Nullable`1 limit) in c:\\VCProject\\SVCodeCampWeb\\WebAPI\\rest\\AttendeesDashboardController.cs:line 97\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
I had this problem too. I fixed it by explicitly naming the assembly that contains the model.
So, if your model is in "Product.DAL.dll", instead of:
metadata=res://*/EFModel.ModelAllTables.csdl|...
put:
metadata=res://Product.DAL/EFModel.ModelAllTables.csdl|...
for all 3 metadata resources
You must add reference to your project that contains the edmx diagram and change the connection string in the Nunit project
Change
<add name="ContainerName" connectionString="metadata=res://*/Diagram.csdl|re.....
By the name of the library in the 3 places in the metadata
<add name="ContainerName"connectionString="metadata=res://File.Data/Diagram.csdl|res://File.Data/Diagra...
"File.Data" is File.Data.dll, library generated by the project that contains the diagram
I have the same problem and solved by running custom tool. Right click on Model.tt file and click on run custom tool and repeat the same for context.tt file and Model.edmx file. Rebuilding the application will works.
Related
I am trying to run the following scaffold the project is in .net 5. and I get this error
All my projects say
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
The one project that references efcore
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Abstractions" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Analyzers" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.4">
Error
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Internal.SemanticVersionComparer' from assembly 'Microsoft.EntityFrameworkCore, Version=5.0.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
at Microsoft.EntityFrameworkCore.Design.OperationExecutor..ctor(IOperationReportHandler reportHandler, IDictionary args)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Microsoft.EntityFrameworkCore.Tools.ReflectionOperationExecutor..ctor(String assembly, String startupAssembly, String projectDir, String dataDirectory, String rootNamespace, String language, String[] remainingArguments)
at Microsoft.EntityFrameworkCore.Tools.Commands.ProjectCommandBase.CreateExecutor(String[] remainingArguments)
at Microsoft.EntityFrameworkCore.Tools.Commands.DbContextScaffoldCommand.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0(String[] args)
at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
Exception has been thrown by the target of an invocation.
Saffold Command
Scaffold-DbContext "Server=1.1.1.1,1433;Initial Catalog=First;Persist
Security Info=False;User
ID=data;Password=data;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection
Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir
Model/DB -Force -Context S3Context -Project S3.Core.DataSync.Framework
-t Data,SyncSales
I have 3 projects 1 project containing EF Core. If I load all three projects and set the project that has references to EF Core as "Set as Startup" I no longer have this issue. As soon as I set what should be the the startup project I get this error
I'm changing a project from using an EDMX file to Code First. The project is one of a few projects in a solution, and it only contains the entities and the DbContext class.
This is what I've done so far:
Removed the old project from the solution (but not deleted it just yet, just renamed the folder).
Added a new class library project to the solution, and given it the same name as the old one.
Used NuGet to add Entity Framework to the new project.
Copied all the entity classes that were generated by the old EDMX file to the new project and included them all.
Copied the DbContext class as well.
Modified the app.config file to change the connection string to a standard connection string without the metadata stuff.
Added a reference to all the other projects that uses to use the old project.
Everything looks good and it compiles with no errors, but when I try to enable-migrations it throws this error:
PM> enable-migrations
Checking if the context targets an existing database...
System.Data.Entity.Core.MetadataException: Unable to load the specified metadata resource.
at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Entity.Core.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.SplitPaths(String paths)
at System.Data.Entity.Core.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetArtifactLoader(DbConnectionOptions effectiveConnectionOptions)
at System.Data.Entity.Core.Metadata.Edm.MetadataCache.GetMetadataWorkspace(DbConnectionOptions effectiveConnectionOptions)
at System.Data.Entity.Core.EntityClient.EntityConnection.GetMetadataWorkspace()
at System.Data.Entity.Core.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
at System.Data.Entity.Core.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor, ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory, Translator translator, ColumnMapFactory columnMapFactory)
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.LazyInternalContext.get_ModelBeingInitialized()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Unable to load the specified metadata resource.
It looks like it still thinks I'm using an EDMX. I also get this error when I try to run the application.
What am I missing?
You have to change the connection string of the starter project (asp.net or winforms project).
I've to admit I'm a little bit confused with how ASP.NET vNext handles dependencies. The thing is that I'd like to use Microsoft Sync Framework with an API I'm implementing in ASP.NET 5. Back in the past I used to install the SDK and then just reference appropriate dlls. It seems that it's not the case with vNext as it's all package driven when it comes to dependencies. Thus I've found Microsoft.SyncFramework package on NuGet and added it as a dependency in my ASP.NET vNext project:
"dependencies": {
"Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
"Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
"Microsoft.AspNet.Mvc": "6.0.0-beta1"
},
"frameworks": {
"aspnet50": {
"dependencies": {
"Microsoft.SyncFramework": "2.1.0.2"
}
},
"aspnetcore50": { }
}
And when VS tries to restore the package, it gets this error:
System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Framework.Runtime.LibraryInformation..ctor(LibraryDescription description)
at Microsoft.Framework.Runtime.LibraryManager.<>c__DisplayClass2.<GetLibraryInfoThunk>b__7(LibraryDescription library)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at Microsoft.Framework.Runtime.LibraryManager.EnsureInitialized()
at Microsoft.Framework.Runtime.LibraryManager.GetLibraryInformation(String name, String aspect)
at Microsoft.Framework.Runtime.ProjectExportProviderHelper.GetExportsRecursive(ICache cache, ILibraryManager manager, ILibraryExportProvider libraryExportProvider, ILibraryKey target, Boolean dependenciesOnly)
at Microsoft.Framework.Runtime.LibraryManager.<>c__DisplayClass0.<GetAllExports>b__1(CacheContext ctx)
at Microsoft.Framework.Runtime.CacheExtensions.<>c__DisplayClass0`1.<Get>b__1(CacheContext ctx)
at Microsoft.Framework.Runtime.Cache.CreateEntry(Object k, Func`2 acquire)
at Microsoft.Framework.Runtime.Cache.<>c__DisplayClass3.<AddEntry>b__4()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at Microsoft.Framework.Runtime.Cache.Get(Object key, Func`2 factory)
at Microsoft.Framework.Runtime.CacheExtensions.Get[T](ICache cache, Object key, Func`2 factory)
at Microsoft.Framework.Runtime.LibraryManager.GetAllExports(String name, String aspect)
at Microsoft.Framework.Runtime.LibraryManager.GetAllExports(String name)
at Microsoft.Framework.Runtime.ProjectMetadataProvider.GetProjectMetadata(String name)
at Microsoft.Framework.DesignTimeHost.ApplicationContext.Initialize(String appPath, String configuration, Boolean triggerBuildOutputs)
at Microsoft.Framework.DesignTimeHost.ApplicationContext.Calculate()
at Microsoft.Framework.DesignTimeHost.ApplicationContext.DoProcessLoop()
at Microsoft.Framework.DesignTimeHost.ApplicationContext.ProcessLoop(Object state)
And as a result I don't have the package included.
Any ideas on how to tackle this?
Apparently ASP.NET vNext dropped support for running *.ps1 scripts in NuGet packages http://forums.asp.net/p/2027698/5842272.aspx
Today EF4.3.1 released.
http://blogs.msdn.com/b/adonet/archive/2012/02/29/ef4-3-1-and-ef5-beta-1-available-on-nuget.aspx.
Follow the blog: http://thedatafarm.com/blog/data-access/using-ef-migrations-with-an-existing-database/. I firstly run:add-migration initial but throw exception as below and no create folder migrations:
PM> add-migration initial
System.Reflection.TargetInvocationException: 调用的目标发生了异常。 ---> System.ArgumentException: 参数不正确。 (异常来自 HRESULT:0x80070057 (E_INVALIDARG))
--- 内部异常堆栈跟踪的结尾 ---
在 System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
在 System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
在 System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
调用的目标发生了异常。
thus, I run Enable-migrations firstly. the folder migrations with Configuration.cs created.
I checked the database, under system tables without dbo._migrationhistory table.
then I run add-migration initial again. throw the same exception Mentioned before.
the Domain model in a project and the datacontext in another project which locate in DAL layer.
in my existing database Security there are several table such as role ,user and so on.
but no migration-history table.
there is only Iset Navigators in my datacontext. no match database tables.
My problem is how to get migration-history table and set up migration?
I finally found that if move the project out of solution Folder. it will work fine. maybe it's a bug.
When I try to use nunit-console.exe to run all the tests in a solution file as such:
nunit-console.exe MyProject.sln
I get the following exception (shown below). However when run the console runner on ANY of the projects in my folder structure, the runner works just fine and never gives me the following exception. I also am pretty certain that the version of the nunit library that I am linking to is the same as the runner that I am using. Also, my solution doesn't reference any projects that are outside the directory structure containing my .sln file.
Does anyone have any clue what I can do!? :(
Thanks!
Phil
NUnit version 2.5.10.11092
Copyright (C) 2002-2009 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.
Runtime Environment -
OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
CLR Version: 4.0.30319.1 ( Net 4.0 )
ProcessModel: Default DomainUsage: Default
Execution Runtime: net-4.0
Unhandled Exception:
System.IO.FileLoadException: Could not load file or assembly 'nunit.framework, Version=2.5.10.11092, Culture=neutral, Pu
blicKeyToken=96d09a1eb7f44a77' or one of its dependencies. The located assembly's manifest definition does not match the
assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'nunit.framework, Version=2.5.10.11092, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77'
Server stack trace:
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount,
IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInsta
ntiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHa
ndle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethod
Arguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope
, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilte
rType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMeth
odInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken,
Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecorate
dTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at NUnit.Core.CoreExtensions.InstallAdhocExtensions(Assembly assembly)
at NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Boolean autoSuites)
at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, String testName, Boolean autoSuites)
at NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
at NUnit.Core.SimpleTestRunner.Load(TestPackage package)
at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
at NUnit.Core.RemoteTestRunner.Load(TestPackage package)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server,
Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExec
uteInContext)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at NUnit.Core.TestRunner.Load(TestPackage package)
at NUnit.Util.TestDomain.Load(TestPackage package)
at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
at NUnit.ConsoleRunner.Runner.Main(String[] args)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Try using the Fusion Log Viewer to see what assembly is failing to load. It should tell you not only what file it is failing on, but where it tried looking for that file.
In my case nunit-console.exe did not respect the assembly redirection from web|app.config. unless you provide /domain=multiple
My Problem:
EntityFrameworkTesting.Moq -> requests Moq, Version=4.2.1409.1722
I had already a newer assembly referenced.
The solution for me was to add /domain=multiple parameter. see the NUnit docs
So I run:
D:\tools\NUnit-2.6.4\bin\nunit-console.exe %SOLUTION_PATH%\Project.sln /config:Release /framework:net-4.0 /domain=multiple /xml=nunit-result.xml