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.
Related
I have simple class library project with a EF Core 5.0-rc1 DbContext that targets .NET 5.0-preview7 with following entites:
public class User
{
public Guid Id { get; set; }
public String Name { get; set; }
public Int32 Age { get; set; }
public virtual IList<Post> Posts { get; set; }
}
public class Post
{
public Guid Id { get; set; }
public String Text { get; set; }
public DateTime PostDate { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
}
Then I've added first migration via dotnet ef migrations add InitialCreate command, created test database and populated some data.
After that I've changed Post.Id data type from Guid to Int32 and created second migration.
According to this SQLite migrations table rebuilds are now available since EF Core 5.0.0-preview8.
Also according to docs AlterColumn command should work for SQLite via table rebuild.
But running context.Database.Migrate(); throws an exception
SQLite Error 20: 'datatype mismatch'.'
Steps to reproduce:
Download test project (test database test.db with some data
is already placed in program output folder).
Compile and run Test console application - context.Database.Migrate(); throws an
exception
Exception StackTrace:
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32
rc, sqlite3 db) at
Microsoft.Data.Sqlite.SqliteDataReader.NextResult() at
Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior) at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery() at
Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject
parameterObject) at
Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection
connection, IReadOnlyDictionary' 2 parameterValues) at
Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1
migrationCommands, IRelationalConnection connection) at
Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String
targetMigration) at
Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade
databaseFacade) at Test.Program.Main(String[] args) in
D:\Test\Test\Program.cs:line 14
Further technical details
EF Core version: 5.0-rc1
Database provider: Microsoft.EntityFrameworkCore.Sqlite 5.0-rc1
Target framework: .NET 5.0-preview7
Operating system: Windows 10 2004 x64
IDE: Visual Studio 2019 16.7.3 Professional
Looks like SQLite teble rebuild is not a magic bullet and work a little differently than I expected. In case of changing data type for a column you should manually write all migrations - check full discussion with EF team.
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.
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?
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.
I have made a project in which i have choose MVC + Web Api template with Authorized attribute.I have made my SQL Data base on Windows Azure and publish my project successfully.I can see the data of the registered user in users table.
Now i wanted to add one more table to my Database but i am not getting how to do it.I know i have to make a model of that table type and update the database.But i don't getting how to write this part in code.I am total newbie in this part.
I have seen Account controller class it is looking just an alien to me :)
can somebody help me.
Step 1: Create the model for your table
public class Comment
{
public int ID { get; set; }
public string Content { get; set; }
public DateTime DateCreated { get; set; }
public virtual ApplicationUser Author { get; set; }
}
Step2: Add a dbSet for this model in your DbContext class
public class DDBContext : DbContext
{
public DDBContext()
{
/* ... */
}
// add the DbSet
public DbSet<Comment> Comments { get; set; }
//... additional models ommitted
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DDBContext, Configuration>());
}
}
Step 3: Enable Migrations
In the packagemanager console issue those commands:
enable-migrations
add-migration MyNewTableAdded
Step 4: Build the project
Step 5: Issue the update-database command in the packagemanager console
There is a detailed explanation on www.asp.net including the process for Azure. Click here!