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).
Related
As part of my continuous integration flow I need to apply the latest migration generated by EntityFramework to a database.
After some research I learned I can use the following script to accomplish that.
#copy migrate.exe to path\to\project\binfolder
Copy-Item packages\EntityFramework*\tools\migrate.exe path\to\project\binFolder
#apply latest migration
path\to\project\binFolder\migrate.exe pathto\projectGenerated.dll /startupConfigurationFile = "pathTo\Web.config"
I am saving this in a file and using power shell to run it.
I have two connection strings inside the web.config file like the following
<connectionStrings>
<add name="firstConnName" connectionString="connectionstring" providerName="System.Data.SqlClient" />
<add name="secondConnName" connectionString="connectionstring" providerName="System.Data.SqlClient" />
And in code I have the following so that entity framework uses secondConnName
public partial class myContext : DbContext
{
static myContext()
{
Database.SetInitializer<repreeContext>(null);
}
public myContext()
: base("Name=secondConnName")
{
Configuration.ProxyCreationEnabled = false;
}
...
I ran the powershell script above and this is the error i am getting
System.Data.Entity.Migrations.Design.ToolingException: No connection string named 'secondConnName' could be fo
und in the application config file.
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
at System.Data.Entity.Migrations.Console.Program.Run()
at System.Data.Entity.Migrations.Console.Program.Main(String[] args)
ERROR: No connection string named 'secondConnName' could be found in the
application config file.
Using EntityFramework 5.0, and Powershell 4.0
Any idea where I went wrong?
Thanks for the help
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
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.
When using EF 4.3.1 migrations every time i need to add a migration or update database i have to use the StartUpProject parameter. Can I set this somewhere so I don't have to keep doing this? I don't want to set my data project as the start up project. My context and migrations are in different projects if that makes a difference.
Exception thrown when not using StartpProject parameter:
update-database -verbose
Using NuGet project 'Data.Deployment'.
Using StartUp project ''.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
Exception has been thrown by the target of an invocation.
At least with Entity Framework 6, to specify the Startup Project use the -StartUpProjectName parameter with update-database:
update-database -StartUpProjectName <String>
You can use the get-help command within Package Manager Console to view possible parameters for commands:
get-help update-database -detailed
Use the StartupProject parameter: Update-database -StartupProject "PROJECTNAME"
I'm not sure if this is what you're talking about, but you can set the default project in the Package Manager Console to the project where your Migrations config resides in; it's the rightmost dropdown list.
This way I've never had to provide the startup project as an argument.
A clean way around this is to attach a Test Project to the solution.
Even if you don't want to write lots of unit tests, it's an appropriate start-up project for a data layer namespace or similar.
That makes your start up issue cleaner, the package manager applies to the whole solution IIRC - so make sure the default project is the one with the migrations folder in it.
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.