Ef migration error when using default connection string on constractor - c#

In my solution I have some database contract project that stores interfaces for contexts and some project for concrete Ef contexts, something like below:
public interface ISampleContext
{
IDbSet<User> Users { get; set; }
IDbSet<Session> Sessions{ get; set; }
}
public class SampleContext : DbContext, ISampleContext
{
IDbSet<User> Users { get; set; }
IDbSet<Session> Sessions { get; set; }
SampleContext() : base("name=EfDefaultConnectionString"){ ... }
SampleContext(string connectionString) : base(connectionString){ ... }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { ... }
}
I run the command for migration (enable, add, update, etc.) by below pattern:
Add-Migration
-Name MigrationName
-ProjectName EfProjectName
-StartUpProjectName EfProjectName
-ConfigurationTypeName EfProjectName
-ConnectionStringName SomeConnectionStringName
But after running the commands, Ef migration fails. For solve problem, I should comment interface(s) and : base("name=EfDefaultConnectionString"). finally, after create migration uncomment code.
My question is why when provide connection string name, package manager console not call the SampleContext(string connectionString) constructor and I get below exception?
No connection string named 'EfDefaultConnectionString' could be found in the application config file.
And second question is can I control the flow of running commands in package manager console?
last question is not exactly related to this problem, but I need now Is there any way run migration commands when "EntityFramework.dll" and "EntityFramework.SqlServer.dll" "copy local" is false?

Related

Migration System.InvalidOperationException using EF MySQL

I'm trying to perform a first EF migration of database, but I get this exception:
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Storage.TypeMappingSourceDependencies' while attempting to activate 'MySql.EntityFrameworkCore.Storage.Internal.MySQLTypeMappingSource'.
I upped stacktrace at imgur:
https://imgur.com/a/OWnsas8
I'm using jetbrains rider (but isn't working at Visual Studio 2022 as well) and this nuget packets:
mysql.entityframeworkcore/6.0.1 and microsoft.entityframeworkcore.design/6.0.1
The command line I used was:
dotnet ef migrations AddInitialMigration
My entire code is:
namespace LibraryDB.db;
internal class CatalogueContext : DbContext
{
public DbSet<Book> catalogue { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("server=localhost;database=libraryDB2;user=username;password=password");
}
}
#####
namespace LibraryDB;
public class Book
{
[Key]
public string Name { get; set; }
public string Publisher { get; set; }
}
I already searched over all internet, but i can't get a resolution for that. Please help-me!
I discovered by myself a resolution for that problem. Creating a DbContext by Command Line to MySQL database connection, I finally get a migration:
dotnet ef dbcontext scaffold "Server=localhost;User Id=youruser;Password=yourpassword;Database=yourdatabase" "Pomelo.EntityFrameworkCore.MySql" -c MyDbContext
I'm going to close question now. Thank you everyone.

Consuming View in EF Code First conflicts with migration

I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework.
I copied the model class and changed its name and added it to the context:
public class ViewIncomingCheck
{
[Key]
public int Id { get; set; }
//...
}
public class CheckDataContext : DbContext
{
public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
//...
}
now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.
How can I use this view in my code?
Edit
My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.
According to what I have done in my project:
First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks
{ get; set; } to your DbConext
Now create a migration something called ViewDbSetAdded
Remove all the code from the both Up and Down method and it will look like as follows:
Migration Code:
public partial class ViewDbSetAdded : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Now run update-database command and it will run an empty migration.

How do I get Entity Framework Code First Migrations to see my models?

I made a new ASP.Net Web Application and enabled migrations on it. I ran add-migration initial and the initial migration does in fact have all the default tables for authentication (dbo.AspNetRoles, dbo.AspNetUserRoles, etc). However, when I create my own context and add an entity model to it, I can't get migrations to acknowledge that model. That is, when I run add-migration added-watchedgame-model I just get an "empty" migration file. So what am I doing wrong? Does my DbContext have to be referenced somehow? can Entity Framework only handle migrations for 1 dbcontext?
ReleaseDateMailerDBContext.cs:
using System.Data.Entity;
using WebApplication4.Models;
namespace WebApplication4.DataAccess
{
public class ReleaseDateMailerDBContext : DbContext
{
public ReleaseDateMailerDBContext() : base("DefaultConnection") { }
public DbSet<WatchedGameModel> WatchedGameModelSet { get; set; }
}
}
WatchedGameModel.cs:
using System.ComponentModel.DataAnnotations;
namespace WebApplication4.Models
{
public class WatchedGameModel
{
public int ID { get; set; }
[MaxLength(1024)]
public string URL { get; set; }
public string Email { get; set; }
public bool EmailSent { get; set; }
}
}
"empty" migration file:
namespace ReleaseDateMailer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addedwatchedgamemodel : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
"Batch Clean" may resolve your porblem.
It suggests that the EF tooling/assemblies are looking in a location other than the default build output location (typically /bin/Debug). The clean command also, incidentally, clears intermediary outputs.
To do a batch clean:
Select Build -> Batch Build
Click Select All
Click Clean
Close dialog, rebuild and re-attempt migration.
While running the add-migration command your package manager console should be pointed to the project having your DBContext class (WebApplication4.DataAccess).
If you have migration in a different project than your web application project (suppose WebApplication4.Web) then you should run the following command:
add-migration "MigrationName" -projectName:WebApplication.DataAccess -startupProjectName:WebApplication4.Web
Hope it helps!!
With the built-in asp.net mvc project, a DbContext class (ApplicationDbContext) is already
created!
When you enter enable-migrations, a migration configuration class is created based on the dbcontext class that it finds.
When you enter add-migration "migrationname", That dbcontext class is what is checked for differences.
So all one has to do is, rather than making one's own class that derives from DbContext, use that one.

Table not mapped using EF code first approach

I'd like to use EF code first approach. I added the database and I generate the tables . Then I added this class
public class Invitation
{
[Key]
public int Id { get; set; }
[DefaultValue(false)]
public bool State { get; set; }
public string Mail { get; set; }
public string Tel { get; set; }
public string Name { get; set; }
public string Qr_code { get; set; }
}
I run these command then :
add-migrations second
update-database
the Up and Down methods of the second class migration are empty!! and no table is added to the database.
The context
public class ApplicationContext: IdentityDbContext<ApplicationUser>
{
public ApplicationContext()
:base("DefaultConnection")
{
Database.SetInitializer<ApplicationContext>(new CreateDatabaseIfNotExists<ApplicationContext>());
}
public static ApplicationContext Create()
{
return new ApplicationContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
So I need to know
What is the reason of this problem?
How can I fix it?
Looks like you forgot to tell Entity Framework about the new table that you want added (DbSet<Invitation>)
Once you add this, Entity Framework should add the table(s) you want added in the Migration script, respectively.
In summation, you would need to add this line :
public DbSet<Invitation> Invitations { get; set; }
and/or
public IDbSet<Invitation> Invitations { get; set; }
and run another Migration Script.
Try adding the following into your ApplicationContext class
public DbSet<Invitation> Invitations { get; set; }
Then running;
Enable-Migration
Add-Migration note_of_changes
Update-Database
I think you need to create an initial migration. If this is your first migration (note that this will clear your existing migration history so only use if you're happy to discard your existing migration history)
Delete your Migrations folder in the solution
Remove your changes (remove the reference to the new table from your DbContext). Note that -IgnoreChanges could well make this step redundant but I can't say for certain.
Remove the MigrationHistory table from your database (it most likely won't exist but you can go ahead and delete it if it is)
Now enable migrations (in package manager console)
Enable-Migrations
Then create your initial migration. This will create a migration matching your existing schema with empty methods
Add-Migration Initial –IgnoreChanges
Update-Database
Then update your DbContext with your new table reference and make any other changes you need to and do
Add-Migration MyChanges
Update-Database
That should apply the changes to the database. Some more info over at MSDN if you need it.

EF6 Code First Migration from Class Library Results in Blank Up/Down

I'm rewriting some code from EF5 into EF6. As part of the process I'm attempting to split my database context logic out into a class library. This worked before when part of the main project but now results in blank up/down methods when running add-migration.
public class SLDBContext : DbContext
{
public SLDBContext()
: base("name=SLApi")
{
System.Data.Entity.Database.SetInitializer(new CreateDatabaseIfNotExists<SLDBContext>());
}
public DbSet<Language> Languages { get; set; }
public DbSet<Template> Templates { get; set; }
public DbSet<TemplateFolder> TemplateFolders { get; set; }
public DbSet<Element> Elements { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
Running add-migration MagicWombat with my class library selected in the Package Manager Console gives me this:
public partial class MagicWombat : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
My seed methods are empty but I would expect it to create me some empty tables non-the-less. Obviously I'm missing something, but what?
If your DbContext is no longer inside your startup project you need to use the -StartUpProjectName switch, so that EF can look at the config file there for the connection string.
add-migration MagicWombat -StartUpProjectName YourProject
if you've selected your class library as default in PM console, otherwise:
add-migration MagicWombat -ProjectName YouClassLibrary -StartUpProjectName YourProject

Categories