Entity Framework 4.3 doesn't create database - c#

I created new project and added the newest entity framework to it (version 4.3). I created classes and the context as in previous EF versions. However, during the very first run when the database should be created (in my case it is SQL Server 2005), I'm receiving the following error:
An error occurred while executing the command definition. See the inner exception for details.
With the following inner exception:
Invalid object name 'dbo.__MigrationHistory'.
As I understand, this table is for migrations, but this table does not exist if there is no database. Am I doing something wrong?
More info:
For testing purposes I created only one class:
public class Test
{
[Key]
public int TestId { get; set;}
public string Name {get; set;}
}
public class Context : DbContext
{
public Context() : base("MyConnection")
{
}
public DbSet<Test> Tests { get; set;}
}
UPDATE 1
After some tests I realized that application is throwing unhandled exception from visual studio and break in visual studio. The exception was System.Data.EntityCommandExecutionException. Once I ignored that expection and didn't stop code execution, database was created.
UPDATE 2
After another few hours working with database I found out that playing with Enable-Migrations option and Update-Database from console also is solving that issue. It is creating database before application start and don't break in Visual Studio.

Could you try removing your constructor to make EF use it's default connection string.
public Context() : base("MyConnection")
{
}
Failing that, could you try updating your database from the Package Manager Console to see if you get any further information.
Update-Database -Verbose
Possibly unrelated in your case, but I get the same error when using MvcMiniProfiler 1.9. If you are using it too, make sure EF profiling is turned off by commenting out the line:
//MiniProfilerEF.Initialize();
Within the MiniProfiler App_Start.
For others experiencing a similar issue, I have found that reenabling migrations from the Package Manager Console can help in certain cases. Make sure you have a copy of your Migration configuration before doing this.
Enable-Migrations -Force

...and just to add one more possible answer for all those facing similar problem
(note: this is an open-ended story seems, as there're obviously some bugs still with the migration part)...
This link came closest to what I needed
Error when running Update-Database with EF 4.3
so, you need to do 3 things (in that order - and I'm referring to an existing project):
(all is in PM console)
Make sure that 'default project' in PM Console is set to your desired project (i.e. for larger solutions) - that doesn't necessarily match your startup project! (and closely watch the comments/response in PM as to whether the actions were made on the project you want)
(1) Enable-Migrations -force
(2) Add-Migration Initial
(3) Update-Database -Verbose
...if you still get an exception in PM console
(4) then you might need to 'move' your project into the root
it sounds silly I know, but that was the main problem on my side - I had a bunch of solution folders and any of the above would fail on projects within solution folders. However, once I moved the project to the root, everything worked fine (no more exceptions, with or w/o first-chance exceptions for CLR turned on or off)...
hope this helps somebody
EDIT: if your data model project (EF CF) is a library - then set that project as a 'default project' in PM console - and run all those things above on that project directly (and have migration configuration etc. created in the lib itself). Otherwise it'd fail (and the same no MigrationHistory exception also appears when your model is a lib - and no migration defined for it, within it - and you have migration defined on the 'main project').
EDIT: you'd need to move both the lib (EF model) and the 'startup' project (calling it) into the root.

Related

How to use Code First Migrations When Domain Models in Separate Project from WebUI?

I have a VS 2017 solution with 2 .Net Core 1.1 projects, 1 is just a class library containing all of my domain models and the other is the actual MVC web application containing the contexts (the ApplicationDbContext & one I created) & all of the EFCore assemblies. I'm trying to enable & use migration on the context I created but having trouble being that the context is in the WebUI project and the models are in the class project. Upon 1st execution of Add-Migration command, I got this error about my target project didn't match my migrations assembly, so I figured out how to get around that by changing the migration assembly in Startup.cs. Add-Migration ended up working but the migration file was created in the class project where the EFCore assemblies are not referenced, thus giving an error on the migration file. I thought maybe I'd try and trick it by moving the file to my WebUI project to update the database, but then figured that may not work & there has to be an easier way of doing this. Does anyone know how to setup code first migrations for EFCore to keep track of modifications and update the database when my domain models are in another project? Any help would be greatly appreciated. Hopefully this isn't too vague. If more info is needed, I'll be all too happy to post. Thanks.
I may not be understanding the question correctly, but have you tried referencing your domain project in your webUI?

Fails to Scaffolding on project which has a reference to edmx

I have Demo solution with two projects like this :
I have installed T4Scaffolding.Install-Package T4Scaffolding
I have added a reference of AdventureWorksModel to my RepoLayer Project and install EF6 .
Now when i try to run the following command :
scaffold repository AdventureWorksModel.Customer to my RepoLayer Project
I get the following exception :
Get-ProjectType : Cannot find a type matching the name
'AdventureWorksModel.Customer'. Try specifying the fully-qualified
type name, including namespace.`
although the same command works successfully when i run it on AdventureWorksModel project !
Here is the steps which you need to do
Class library having AdventureWorksModel EDMX (already present)
Class library "RepoLayer" which above AdventureWorksModel library, EF 6 installed (already present)
In the "RepoLayer" library, please T4Scaffolding.Core.VS2015 and T4Scaffolding.VS2015 NuGet packages. I hope your using VS 2015
Run the scaffolding command scaffold repository AdvwrksModel.Customer for "RepoLayer" library. The repository and DbContext class gets created successfully. Here is screenshot
Update related to EDMX name from above screen shot
The command
scaffold repository AdvwrksModel.Customer
gives us important thought "AdvwrksModel" is EDMX name and namespace should be "AdvwrksModel". Then it will work fine.
From code link provided; After building, it gave same error what you mentioned in question, then after investigation it was namespace issue. Attaching screenshot with points 1, 2, 3, 4 should be "SledModel" i.e. EDMX name. Point 5 is generated repository for Race
I guess this will solve your problem. I am not sure how the namespace was different then EDMX name.

Entity Framework Import-Module : The specified module '...EntityFramework.psd1' was not loaded

Recently I decided to use Entity Framework for a personal project.
From my Visual Studio 2013 community edition and using NuGet I installed the latest version of the framework (nuget version 2.8.60318.734 and Entity Framework 6.1.3)
Everything seems to work OK I was able to perform simple CRUD operations, till I needed to update my model.
After it, of course I got the error message:
“Additional information: The model backing the 'MyContext' context has changed since
the database was created. Consider using Code First Migrations to update the database
(http://go.microsoft.com/fwlink/?LinkId=238269).”
Seems an appropriate error message, I just need to Enable-Migrations.
Switch to Package Manager Console and there was a message in bright red background
PM> Import-Module : The specified module 'D:\[MyProjects]\[ProfOfConcept]\EntityFrameworkInvalidFilepath\packages\EntityFramework.6.1.3\tools\EntityFramework.psd1' was not loaded because
no valid module file was found in any module directory.
At D:\[MyProjects]\[ProfOfConcept]\EntityFrameworkInvalidFilepath\packages\EntityFramework.6.1.3\tools\init.ps1:8 char:14
+ Import-Module <<<< (Join-Path $toolsPath EntityFramework.psd1)
+ CategoryInfo : ResourceUnavailable: (D:\[MyProjects]...yFramework.psd1:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
Hmmmm something is wrong, I guess some needed part of the framework was not correctly installed, but let's check the file. The file was present, and the content seemed OK.
Alright let's try to reinstall it, just in case something went wrong at the first time. Using NuGet I tried to uninstall, and reinstall.
Checking Package Manager Console, again the same dreaded error!
Hmmm, let's try to do the uninstall /reinstall from the Package Manager Console. Again the same error!
After spending more time trying to Google similar problems I came across someone describing a similar problem Entity Framework with NuGet - Import-Module error in init.ps1 Tried that… no luck.
So what is really going on? In a Eureka moment I thought… hold on, what was my project path?
D:\[MyProjects]\[ProofOfConcept]\….
Could it be? Could the square brackets be the reason?
Create a copy the project to a simple path (d:\tmp\myProject) start the Visual Studio, enter Package Management Console, …. no error !
Enable-Migrations
PM> Enable-Migrations
Checking if the context targets an existing database...
Detected database created with a database initializer. Scaffolded migration '201504051040353_InitialCreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run Enable-Migrations specifying the -EnableAutomaticMigrations parameter.
Code First Migrations enabled for project EntityFrameworkInvalidFilepath.
That's it!! The square brackets are the culprits
So the bottom line is this, if you are using Entity Framework don’t use [ ] in the path.
I recently had the same issue with NuGet not installing EF 6.1.3 properly because the EntityFramework.psd1 file wasn't being imported. Uninstalling and re-installing EF through Visual Studio didn't help.
What worked for me was to quit VS, navigate to '[Project Root Directory]\packages' and delete the EntityFramework6.1.3 directory. When you restart VS and go to the package manager console, it will let you know that there are modules missing and ask if you want to import them. When you click 'Reload' EF 6.1.3 is installed properly under the 'packages' directory.
In my case I'm using the 2015RC, which has a lot of issues with EF migrations.

Not able to instantiate a context from all project within a solution

I have a solution where there are following projects:
a context and entities developed under code-first approach.
A class library that present some business objects. the objets are using the EF context and its object for a DataAccess needs.
The solution has unit test of the business objects
I am able to execute my unit test successfully.
Now I have added a MVC 5 project where I would like to inject my business object. I have created a controller and view and put the same peace of code which has been passed in one of my unit test and also added the project web config proper entity framework and connnection strings sections. When I am executing the code I am facing the follwing error:
Migrations is enabled for context 'DatabaseContext' but the database
does not exist or contains no mapped tables. Use Migrations to create
the database and its tables, for example by running the
'Update-Database' command from the Package Manager Console.
When I am debugging my code I see that I am getting throug theese instructions
Database.SetInitializer(new ModelContextStrategy());
and
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
but still my result is negative, although everething works fine in my unit testss...
in case I am doing the unit tests first the db is get created and all unit test are through, and then I am starting the MVC application I am getting:
The model backing the 'DatabaseContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database
What I am missing or doing wrong? (specific nuget packages installation for the mvc project? )
the problem was solved as soon a I enabled the entity framework for my MVC project
Install-Package EntityFramework -Version 6.1.0

Entity Framework 4.3 migrations error

I've just installed EF 4.3-beta1 for the migrations goodness, and I can't get it working. The error I get:
PM> Update-Database -Verbose
Using NuGet project 'Project.Domain'.
Using StartUp project 'ProjectWebSite'.
System.InvalidOperationException: No migrations configuration type was found in the assembly 'Project.Domain'.
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.FindConfiguration()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator()
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
No migrations configuration type was found in the assembly 'Project.Domain'.
I've added a new column to 2 EF classes:
public class MasterInstance
{
public int MasterInstanceId { get; set; }
[Required] public string HostName { get; set; }
[Required] public string Name { get; set; } /* <-- THIS IS NEW */
[Required] public string ConnectionString { get; set; }
public virtual ICollection<MasterInstanceLocation> MasterInstanceLocations { get; set; }
}
And my DbContext looks like this:
public class ProjectDontext: DbContext, IProjectContext
{
public IDbSet<Installer> Installers { get; set; }
public IDbSet<MasterInstance> MasterInstances { get; set; }
public IDbSet<MasterInstanceLocation> MasterInstanceLocations { get; set; }
}
Any ideas? My EF classes & context live in a separate assembly (Project.Domain). I've tried running the update-database in the context of both the main website and the domain project, and I get the same error either way.
-- EDIT --
Solution found. It turns out, that you need to enable migrations for your project. You can do this by running Enable-Migrations in the NuGet console (make sure you have the right project selected - for me this was the project.domain project).
This walkthrough provides more information
Solution found. It turns out, that you need to enable migrations for your project. You can do this by running Enable-Migrations in the NuGet console (make sure you have the right project selected - for me this was the project.domain project).
This walkthrough provides more information
Sometimes, even if you have enabled migration, this problem can occur. It means that configuration file has been deleted. In this case, you can run
Enable-Migrations -Force
in the Package Manager Console. -Force parameter is to override migration configuration file.
If you had already enabled migrations and just started seeing this error after some windows updates, ensure you are using the same version of Entity Framework across all projects using the NuGet Package Manager.
Recent windows updates may have installed a newer version of Entity Framework into your active project.
Background: Around 16 Mar 2016, I started getting the "no migrations configuration type" error when trying to add migrations to a project where I had already enabled migrations and had successfully done migrations before.
I noticed that around March 10, a new stable version of Entity Framework 6 had been released.
If I specified the -ContextTypeName parameter in the enable-migrations command, I got an error indicating the migrations were already enabled.
Another error I got as I was troubleshooting indicated that the Configuration type was not inheriting from the System.Data.Entity.ModelConfiguration.EntityTypeConfiguration, even though it was.
That led me to believe different versions of the Entity Framework were conflicting.
Resolution:
1) Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution
2) (Not sure if this step is necessary, but..) I updated my version of the Nuget Package Manager to the latest version. Also, after updating my version of Nuget Package Manager, I had to restart Visual Studio twice before the NuGet Command line would work properly.
3) Tools -> Nuget package Manager -> Manage Nuget Packages for Solution -> Search Installed packages -> Type Entity Framework
a. You may see more than one version of Entity Framework there.
b. Click Manage on each version of Entity Framework and ensure that your projects are using the SAME version of Entity Framework.
•Uncheck the version of Entity Framework that you are not using and for the version of Entity Framework you ARE using make sure it is checked across your projects that need it.
Again, as noted in step 2, I had to restart visual studio twice to get the NuGet Package Manager Console to work properly after updating my version of the NuGet Package Manager. I got an error starting the console the first time, and "exception calling createinstancefrom with 8 arguments could not load file or assembly EntityFramework" when running the enable-migrations command the second time.
Restarting visual studio seemed to resolve those issues, however.
For me, this error occurred because I had the wrong project selected in the Package Manager Console's "Default Project" in VS2019.
Even when migration are enabled, the described behavior can occur if an incorrect Default Project has been chosen in the drop-down menu of the Package Manager Console. A non-graphical way around is to expand the command you are using, and specify the correct project name with the parameter -ProjectName
Update-Database -Verbose -ProjectName TheCorrectProjectName
You might still get a warning like
Cannot determine a valid start-up project. Using project 'TheCorrectProjectName' instead. Your configuration file and working directory may not be set as expected. Use the -StartUpProjectName parameter to set one explicitly.
Nevertheless, this additional command line parameter solved the issue for me.

Categories

Resources