Code First Environment
I'm trying to update the database from package Manager console. If my domain class changes, I have to drop and create the database. Instead of dropping the database, how can I update the database?
Commands
By using this command, I installed the Entity Framework successfully.
PM> Install-Package EntityFramework
By using this command, it created the Migration file in my project.
PM> Enable-Migrations
By using this command, I may update the table but I have a problem here.
PM> Update-Database
Error
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
Doubt is here
Sometimes it may update if only one field changes in POCO Class. For example I have updated the more number of Domain class. How can I update the database from Package manager Console?
You can specify connection string via ConnectionString parameter:
Update-Database -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose
Also you need to use this parameter with the same value for Add-Migration command:
Add-Migration Version_Name -ConnectionString "data source=server_name;initial catalog=db_name;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" -ConnectionProviderName "System.Data.SqlClient" -Verbose
I used
Enable-Migrations -EnableAutomaticMigrations -Force
then
Update-Database
And this migrated my changes (additional columns) while preserving my test data. I think this is the laziest option while prototyping.
Looks like you have multiple issues. Regarding not wanting to drop and recreate the database, that is determined by your database initializer. If you want to use migrations you change it to MigrateDatabaseToLatestVersion. http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm
Second, it doesn't matter how many fields you change, they will be rolled into a single migration based on changes from the last migration.
Third, as the others have pointed out, it seems you have a connection string issue. While you can add that to Add-Migration and Update-Migration I would probably fix it in the application. I set mine in the constructor of my context which points to my config file (web.config for ASP.NET).
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("MyConnection", throwIfV1Schema: false)
{
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext, MyObjextContextMigration>());
}
...
Where to put the connection string?
You do not need to specify it with every command in the package manager console. You can put it in appsettings.json in the project where your DbContext class (read "from DbContext derived class") resides.
{
"ConnectionStrings": {
"MyConnectionString": "Server=yourServer;Port=5432;Database=yourDatabase;User Id=yourDatabaseUsername;Password=yourDatabasePassword;"
}
}
It will be used for migrations.
Important: If you have multiple projects in your solution, you must select the project in the 'Default project'-dropdown (in the Package manager Console) and you must set the project as your startup project (in the Solution Explorer).
Failing to do so, might cause the wrong appsettings.json to be used with an incorrect/different connectionstring.
This was my experience with EF Core 2.1 and probably applies to the other versions of EF.
You need to update SSDT
go to tools> extension and updates > updates > SQL server data tools
Related
I have a project in blazor wasm, in the appsettings.json file I have two connection strings, one points to the development database and the other to the production database, the production database is a copy of the database of development data.
appsettings. json file:
"AllowedHosts": "*",
"ConnectionStrings": {
"SqlConnectionDesarrollo": "Data Source=10.0.0.41;Initial Catalog=QaInventarios;User ID=Innovacion;Password=***;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
"SqlConnectionProduccion": "Data Source=10.0.0.41;Initial Catalog=Inventarios;User ID=Innovacion;Password=***;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
},
startup file:
services.AddDbContext<ApplicationDbContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionDesarrollo")));
the problem is that to perform a migration what I do is comment a connection string depending on the database I want to use and changing the name in the startup, I know it's a bad practice but I don't know how to optimize this, then I execute:
Add-Migration NameMigration
Update-Database
to perform a migration, in the development database it works fine, a new migration is created and the changes are made, then I run the Update-Database command again to update the production database and the changes are not made and are not added the new migration and the changes are not made, the same thing happens if I delete any migration with Remove-Migration -Force and then an Update-Database
there are inconsistencies in my database, how can I perform
migrations, changes in both and that they remain exactly the same ??
In EF Core 5.0, a connection string option is introduced in the EF Core CLI tool.
Example
For Development
dotnet ef database update --connection <Development Connection string>
And for Production.
dotnet ef database update --connection <Production Connection string>
Documentation about dotnet ef update
I'm after running into a problem with using Database-Migrations on my asp.net mvc project because I am using 2 local databases. I now have 2 databases; 1 which was created on project startup for identity user management like users, user roles etc. (aspnet-IdentityTest-201~). I Enabled-Migrations on this database in order to Seed() an admin member into it and everything was working fine.
The 2nd database was created after this using the code first database approach to store model data. Now my question, since my project already has migrations enabled (on the 1st Db), how do I enable migrations on my 2nd Db also? Currently when I run Update-Database, it targets 'aspnet-IdentityTest-20190707071058'. I would like to be able to run this command for my 'IdentityTest.Models.TestDb' also (with automatic migration enabled).
I'm afraid to run 'Enable-Migrations -ContextTypeName IdentityTest.Models.TestDb' again as the last time I did this, it deleted my current config.cs file which included my Seed() for admins and I was left with a new config file for just the TestDb context. The project also failed to build after this
Could somebody please advise if there a way for my 2 databases to have migrations enabled? Do they have to share the same migrations/config.cs file? If this is not possible, using the code first approach; how do I make my project use aspnet-IdentityTest-201~ Db for storing model information instead of creating a new Db like it did with IdentityTest.Models.TestDb?
Thanks in advance!
First I took a solution where I successfully code firsted a db. I changed all occurrences of my db name and suffix it with 2db. I create another connection and call it {..}2 with catalog name {..}2dbSecond. I then delete my Migrations folder. I split out my context file into two contexts and have DbSet<> included in each appropriately.
typed:
enable-migrations -projectname contosouniversitydal -contexttypename schoolcontext
in the added migrations folder, in configration.cs, added the a seed method
Add-Migration InitialCreateContext1 -ProjectName contosouniversitydal -configurationtypename configuration -connectionstring schoolcontext
Update-database -projectname contosouniversitydal -configurationtypename configuration -connectionstringname schoolcontext
I then do the similar for the other context.
You can use https://coding.abel.nu/2012/03/ef-migrations-command-reference
Enable-Migrations has a -MigrationsDirectory option, so you can split among two different databases.
I want to create a migration for a second and subsequent databases that's in a class library different from the project that uses it. There is a wrinkle. I will never know the connection string until a user logs in and I can get it from a catalog database (saas).
For the catalog database I used the solution from this site. That was fine - This database has its connection string in appsettings.json and can uses dependency injection.
The client databases are all going to be identical using the same migration. My problem is, I dont know how to create this initial migration from the Package Manager Console..
I did try to run this:
dotnet ef migrations add INITIAL --context APIcontext -s ../Jobsledger.API
and its given me the following error:
No database provider has been configured for this DbContext.
Which I expected.
Given that CodingBlast solution (above) to running migrations in a different class library requires a connection which I don't have and requires the database connection to be registered at startup...
..and given that this migration is to be used by every user database to be created how do I create it and of course use it?
I did answer similar question here.
You can implement IDesignTimeDbContextFactory where you instantiate DbContext with no connection string.
For the different library, you can use --project and --startup-project parameters.
Here is an example what I'm using to generate migrations script:
dotnet ef migrations script --context MyDbContext --output migrations.sql --project "./MyApp.Data" --startup-project "./MyApp.Data"
This question has been asked many times in different flavors on SO. I have gone through all the answers and burn lot of time. I just can not seem to get this working.
I have been working on asp.net mvc Entity Framework, SQL server app. I already have an existing database, tables, etc. and every thing is working. I just need to add a new column to the table.
So.. I added a property in the model class, so that I could add the column to the table. But with no success.
So I do the steps in the following order.
Add the field in my model class.
[Required]
public string EmailSubject{ get; set; }
Then I delete the folder Migrations in my asp.net mvc project containing Configuration.cs class
Then in Package Manager Console, I issue following command successfully.
Enable-Migrations -ContextTypeName AppointmentReminder.Data.ReminderDb -Force
Then I set the property true as follows
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
Then I issue the following command in package manager console.
Update-Database -Verbose -Force
Here is what my connection string to default connection to the database looks like
Data Source=(LocalDb)\v11.0;AttachDbFilename=C:\practice\AppointmentReminder4\AppointmentReminder4\App_Data\aspnet-AppointmentReminder4-20141202060615.mdf;Initial Catalog=aspnet-AppointmentReminder4-20141202060615;Integrated Security=True
But I am UNABLE to add the new column in my desired table.
Edit 1
I updated the model as follows without the required attribute and executed all of the above steps but I was still NOT able to add the column to the table.
public string EmailBody { get; set; }
Here are all the commands and their output.
PM> Enable-Migrations -ContextTypeName AppointmentReminder.Data.ReminderDb -Force
Checking if the context targets an existing database...
Code First Migrations enabled for project AppointmentReminder4.
PM> Update-Database -Verbose -Force
Using StartUp project 'AppointmentReminder4'.
Using NuGet project 'AppointmentReminder4'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'aspnet-AppointmentReminder4-20141202060615' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Running Seed method.
PM> Update-Database -Verbose -Force
Using StartUp project 'AppointmentReminder4'.
Using NuGet project 'AppointmentReminder4'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'aspnet-AppointmentReminder4-20141202060615' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Running Seed method.
PM>
Edit 2
Finally resolved this issue. All my steps above were correct. Except I was editing my model class as opposed to actual data class that is actually tied to the ReminderDb (EF object). After I updated the correct class with the property, every thing worked successfully. Thanks to all those who responded with help!
Because the field is required, you need to specify a default value. Edit your migration file, find the line adding your column, and specify what the default value should be:
public override void Up()
{
AddColumn("dbo.MyTable", "EmailSubject", c => c.String(nullable: false, defaultValue: ""));
}
For reference:
Default value for Required fields in Entity Framework migrations?
Edit: Based on your edit, you need to create a migration before you try to update. See this example for how you typically use it.
However, if you're trying to apply Code First Migrations to an existing database, this article may help: Code First Migrations with an existing database
You decorated the new column with required attribute. If that table has already some rows those rows can not have that column.
Remove required. Than do migrations, populate all rows with data.
Make property required and migrate again.
Ok, so I've read the other threads and I'm still not getting anywhere. I have my project set as Startup, I have a connection string in the App.config. I'm using LocalDb in VS2013.
If I delete my database, it creates it ok, BUT, if I try
PM> Enable-Migrations
it tells me that Migrations have already been enabled in project TestCodeFirst. If I then try
PM> Update-Database
it tells me No migrations configuration type was found in the assembly 'TestCodeFirst', and suggests that I try to Enable-Migrations. I have tried adding the -Force parameter. The Migrations folder has only Configuration.cs, and in that file, I've tried setting AutomaticMigrationsEnabled both true and false, with no difference. I'm not lost, cause I can always delete my DB and rerun, but I don't see any way to make the migrations feature work as advertised. Confession: At one point, I took PM's suggestion and tried deleting the Migrations folder. That may have been a mistake.
I have this code snippet in my Program.cs file (I'm just testing this in a console app):
class Program
{
static void Main(string[] args)
{
using (TestContext db = new TestContext())
{
...
Db.ThisOrThat.Add(stuff);
Db.SaveChanges();
...
}
}
}
The Entity Framework Code First approach creates your database automatically, a table will be automatically added to the database by the Code First that is helpful to record the schema of database synchronization with the related model class. Entity Framework throws an error, the database is not synchronized with the class.
To perform the Code First Migration in the database:
Delete the MDF file of the database
Open Package Manager Console and write the following command
Enable-Migrations -ContextTypeName ConsoleApp.Models.TestContext
It creates the Configurations.csclass, then you can edit your code
After Building the application enter the following command in the Package Manager Console:
add-migration Initial
update-database
Note: If you receive an error then you need to ensure that the mdf file is deleted permanently from the App_Data folder. Otherwise you can go to the SQL Server Object Explorer, expand the localDb server and in the Database option ensure that the mdf file is deleted.
Debug the appliction
You'll need to run the "Add-Migration" command that will actually add the migration that the 'Update-Database' command will run:
Code First Migrations
"Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created"