I seem to be having a hard time finding the information I need to implement EF Core. I've read a lot of articles, and watched videos such as Getting Started with Entity Framework Core [1 of 5]. But none of these articles and videos assume a Razor Pages project created with the latest version of Visual Studio (16.3.6).
I'm much prefer (and am already familiar with) database first, but Microsoft has decided we need to be code first.
So I manually created my entity classes and ran the Add-Migration command. (Note that 00000000000000_CreateIdentitySchema.cs was created by Visual Studio when I created the project.)
It runs successfully but creates an empty Migration class.
public partial class InitialTaskClasses : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
Is there anyway to have it incorporate my entity classes into the migration?
*Note that I've already done an update-database command, which added the entity classes to my database.
public DbSet<Area> Area{ get; set; }
public DbSet<Goal> Goal{ get; set; }
public DbSet<Task> Task{ get; set; }
This should go as properties inside your ApplicationDbContext
Related
For a while now I've had a custom migration in my Entity Framework Core project that creates some SQL objects - stored procedures and functions.
It looks something like this:
using Microsoft.EntityFrameworkCore.Migrations;
namespace CaseFlow_API.Migrations
{
public partial class AdditionalSQLObjects : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
// Functions
var f_exampleFunction = #"CREATE OR REPLACE FUNCTION public.f_exampleFunction(
character varying,
character varying,
character varying,
integer)
/*
SOME SQL CODE
*/
";
migrationBuilder.Sql(f_exampleFunction);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
However now it stopped working - functions and procedures are not created when updating the db. I don't think I changed anything in how migrations are created. What I would do usually is that I'd run
dotnet ef migrations add Initial
dotnet ef database update
I tried dropping all migrations, dropping the database, recreating the AdditionalSQLObjects.cs class. I have no idea how to debug/fix this.
Can you please point me to places where I can fix this?
Ok, so the custom migration finally works. Here's what I did (added class attributes):
[DbContext(typeof(CaseflowingContext))]
[Migration("CustomMigration_AdditionalSQLObjects")]
public partial class AdditionalSQLObjects : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
//miration code
}
}
I have no idea what happened, because this migration used to work without the attributes, but I'll take it.
I'm an experienced php developer and am attempting my hand at learning Microsoft Entity Framework. My backend Database is Oracle and I'm using ODP.Net as my connection. I've installed VS2019 Community and am working through several tutorials.
Oracle Entity Framework Core Introduction
Entity Framework Best Practices
Microsoft Create a Data Access Layer
EntityFrameworkCore
I'm struggling with trying to have my C# library (DAL) work well with my C# winforms projects. My DAL is a .NET Standard 2.0 project and my winforms projects is .NET Framework 4.7.2. My solution is setup as follows.
C# Solution
Project 1 - C# Library (DAL) - .NET Standard 2.0
Nuget Dependencies
Microsoft.EntityFrameworkCore.Design (2.2.6)
Microsoft.EntityFrameworkCore.Tools (2.2.6)
Oracle.EntityFrameworkCore(2.19.60)
Project 2 - C# Winforms - .NET Framework 4.7.2
Nuget Dependencies
Microsoft.EntityFrameworkCore(2.2.6)
Oracle.EntityFrameworkCore(2.19.60)
Oracle.ManagedDataAccess.Core (2.19.60)
Code pieces of code are in the DAL (project 1)
DbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseOracle(#"<myConnString>");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new PlatePurchaseOrderConfiguration());
}
public DbSet<PlatePurchaseOrder> LtPurchaseOrders { get; set; }
}
ModelConfiguration
class PlatePurchaseOrderConfiguration : IEntityTypeConfiguration<PlatePurchaseOrder>
{
public void Configure(EntityTypeBuilder<PlatePurchaseOrder> builder)
{
builder.HasKey(t => t.Id);
}
}
Model
public class PlatePurchaseOrder
{
public int Id { get; set; }
public bool IsExpeditied { get; set; }
public DateTime ExpectedReturnDate { get; set; }
}
This is the code behind the startup winforms (project 2)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var context = new PlatePurchaseOrderContext();
var query = context.LtPurchaseOrders.ToList();
}
}
And upon running my code I get, an error at the .ToList() command of
Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.3.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51
I have to imagine that I'm mixing projects and .NET components probably messing things up. Is there a good way around this? What should I be doing to correctly setup this Solution?
I am making a C# MVC application using Entity Framework 6.2.0 Everything was going fine until today when I tried to do some migrations.
I had no problem with migrating a week ago but I have no idea what might have caused the error in the package manager:
No DbContext was found in assembly 'Data'. Ensure that you're using
the correct assembly and that the type is neither abstract nor
generic.
I tried reinstalling Entity Framework and made sure that the "Default project" is the right one. I already have a context file that worked properly.
This is my GameContext.cs code:
public class GameContext :DbContext
{
public GameContext()
:base ("name=GameContext")
{
}
public DbSet<Game> Game { get; set; }
public DbSet<Account> Account { get; set; }
}
I need to find a way to fix this problem and manage to update my database.
You maybe need to select ProjectName.Data in project management console
Try adding your assembly name when registering the service, you can find assembly name by going to project properties.
services.AddDbContextPool<AppDbContext>
(
dbContextOptionsBuilder =>
{
dbContextOptionsBuilder.UseSqlServer("yourConnection",
optionsSqlServer => { optionsSqlServer.MigrationsAssembly("ADD_YOUR_ASSEMBLY_NAME");});
}
);
I'm using EF6.0 and implementing my db with SQLServerDatabaseProject.
I want to use the EF Migration tools for Database migration. but since I have my database on DbProject I want all my migration files to be SQLFiles (not c#)
So I would like to know if EF supports this feature and if not, is it possible to write a new Migration class which keeps the EF features but works this way?
Please also consider that I don't want EF to generate my migrations but I would like to be able to use other migration commands such as update-database and ...
==MORE DETAILS ABOUT THE QUESTION==
I don't want to have c# classes load my sql files. The sql files must be saved for up and down migrations directly and be treated exactly as if they are the DbMigration classes.
A simple example of Migrations dir would be something like this:
Migrations
-> up
-> 201510060807125_alter-course-change-family.sql
-> 201510060813136_alter-course-add-mark-column.sql
-> down
-> 201510060807125_alter-course-change-family.sql
-> 201510060813136_alter-course-add-mark-column.sql
Simply in the migration class use SqlFile extension method:
public partial class MyFancyMigration : DbMigration
{
public override void Up()
{
SqlFile("myUpSQLFile.sql");
}
public override void Down()
{
SqlFile("myDownSQLFile.sql");
}
}
Although you can use SqlFile method, I suggest you to write this on Seed method of your Configuration.cs file in your migration folder.
internal sealed class Configuration : DbMigrationConfiguration<YourDbContext>
{
protected override void Seed(YourDbContext context)
{
base.Seed(context);
context.Database.ExecuteSqlCommand(FileReadAllText("migration.sql"));
}
}
If you write migrations in Up method. It will be executed per each migration when you update the database, which I think you don't expect.
What you want is that your scripts run per each Update-Database. (Not per each migration in it)
Ok, so I'm relying completely on my migrations and seed code to maintain all database structure and initial data. Because of that, I'm facing a situation where all the changes I'm doing at this version are made directly on the database (Stored Procs and Updates) and nothing has changed on the C# code itself.
The question is: Since I want to do those DataBase specific changes using a new migration (and an "add-migration" will do nothing - cause the code hasn't change), how can I force a new empty code first migration to put my changes manually on it?
In the package manager console issue the command
Add-Migration "My new empty migration"
This will generate this migration template
public partial class Mynewemptymigration : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
You can then create your own custom up and down migration steps. If you model is not up to date there will be migration code in the up and down. In that case you'll have to get your model up to date and then add a new empty migration.
You have to add an empty migration and add the code to the Up and Down method manually. I have found that people tend to think that the code for those methods have to be generated by the tool similar to ".designer" files and this is not the case. In fact more often than not i have found my self editing and adding code there.
For this purpose I place all the sql code that i have to execute in scripts files and the execute then in the Up methods like this:
public override void Up(){
var dirBase = AppDomain.CurrentDomain.BaseDirectory.Replace(#"\bin",string.Empty) + #"\Migrations\SqlScripts";
Sql(File.ReadAllText(dirBase + #"\CreateMyViews.sql"));
Sql(File.ReadAllText(dirBase + #"\CreateMySproc.sql"));
}
public override void Down(){
var dirBase = AppDomain.CurrentDomain.BaseDirectory.Replace(#"\bin",string.Empty) + #"\Migrations\SqlScripts";
Sql(File.ReadAllText(dirBase + #"\DropMySproc.sql"));
Sql(File.ReadAllText(dirBase + #"\DropMyViews.sql"));
}
I recomend you read this link:
http://elegantcode.com/2012/04/12/entity-framework-migrations-tips/
This is a more up-to-date answer...
In Package Manager Console in Visual Studio, add an empty migration targeting your Database context.
add-migration SeedingFacilityTable -context YourDbContextName
It'll create an empty migration provided you don't have any other DB changes to be applied.
Inside the Up method, write the following:
public partial class SeedingFacilityTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(#"Put as many SQL commands as you want here");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
Then run the following command:
update-database -context YourDbContextName
Add-migration actually do exactly what's asked for.
You can just run dotnet ef migrations add or Add-Migration in the package manager console (as mentioned by David) to generate a class with empty Up and Down methods. Then just put your changes inside that class as usual.