I am using entity framework code first approach and have following model and db context.
public class Patient
{
public int Id { get; set; }
public string FirstName { get; set; }
}
public class PatientContext:DbContext
{
public DbSet<Patient> Persons { get; set; }
}
Now to have the model created in database I have to Run Enable Migration and if any changes then have to run Update database using package manager console.
But is there any way I can do that using code. So when ever some one run console application it will create all table schema.
class Program
{
static void Main(string[] args)
{
//Code to Create my tables
//Something similar to enable migration and update database
}
}
I can have a record created inside main app and that will create the table structure, but creating an record to create table structure seems redundant. Also , if there are any mode changes, following code will throw an exception.
Is there a better approach?
static void Main(string[] args)
{
using (PatientContext pcontext = new DatabaseMigApp.PatientContext())
{
pcontext.Patients.Add(new Patient() { FirstName = "Steve",Id = 1});
pcontext.SaveChanges();
}
}
Yes, there is. You will have to run Enable-Migrations –EnableAutomaticMigrations from package manager console first, so that it generates a Configuration class as follows:
internal sealed class Configuration : DbMigrationsConfiguration<DatabaseMigApp.PatientContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(DatabaseMigApp.PatientContext context)
{
}
}
Then you may update the Program.cs as follows to automatically migrate to the latest version based on your model changes:
using System.Data.Entity;
class Program
{
static void Main(string[] args)
{
using (PatientContext pcontext = new DatabaseMigApp.PatientContext())
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<PatientContext, Configuration>());
pcontext.Database.Initialize(true);
}
}
}
If you do not wish to use automatic migrations and generate them manually (for more control), you could turn off the automatic migrations and add-migration each time you change your model. The code in the program.cs would still suffice to update your database when you run the console application.
Read more about automatic migrations here
Related
I am doing a bookstore project and I first created one table for the adding book.
So I want to add login and signup pages and store to the database, but I am confused about how I can add another table or create tables related to my need using migrations. I have attached my DbContext class.
Forgive me my English is not so good. I am waiting for your answers. Thanks
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CODEwithZAKI.Data
{
public class BookStoreContext : DbContext
{
public BookStoreContext(DbContextOptions<BookStoreContext> options)
: base(options)
{
}
public DbSet<Books> Books { get; set; }
}
}
Dbcontext Class
For how to add a new table to the database with ef core code first, you can follow the below steps:
1.Create your new table as a model
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
//other properties
}
2.Add its entry in DbContext class
public class BookStoreContext : DbContext
{
public BookStoreContext(DbContextOptions<BookStoreContext> options)
: base(options)
{
}
public DbSet<Books> Books { get; set; }
public DbSet<Author> Authors { get; set; }
}
3.Create a new migration with the addition of Posts in Package Manager Console
Add-Migration AuthorMigration
4.Update database
Update-Database
To add new tables to you database using migrations is simply a matter of extending your BookStoreContext with the new sets and then running the migration commands. As an example using dotnet command.
Generate the new migration script:
dotnet ef migrations add DESCRIPTION_OF_YOUR_MIGRATION
Run the migration:
dotnet ef database update
And that's it. Everytime you add new records to your BookStoreContext you just go through the above two commands to run the EF Core migration process.
PS For login/authentication/identity it is recommended to utilize ASP.NET Core Identity.
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.
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'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.
I've previously used NHibernate and Fluent Migrator in projects to create a database (if it didn't already exist) and update the schema through migration scripts. I'm looking over Entity Framework (6) to do a comparison and I'm having trouble replicating that functionality.
In my App.config, I've set up my connection string and db providers. I then went ahead and created a data model that I would like to be represented as a table in the database.
namespace DataModels
{
public class StoreClient
{
public int Id;
public string DisplayName;
public StoreClient()
{
}
}
}
I then went ahead and created a database context.
namespace DataModels
{
public class StoreContext : DbContext
{
public DbSet<StoreClient> StoreClients { get; set; }
}
}
On service start I created an instance of StoreContext and tried to add and call db.SaveChanges();, but this is failing because there is no schema that matches my StoreClient.
My question is simple. How do I configure my StoreContext (or EF in general) to automatically create my database schema, and how do I set it up to migrate when I make changes to that schema?
This seems simple, but my searching around hasn't gotten me anything that looks remotely familiar coming from the NHibernate world.
If you want your db to be created automatically try to put some code in your Application_Start() method.
for example:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, Configuration>());
StoreContext context = new StoreContext();
context.Database.Initialize(true);
Where Configuration class is created upon automatic migrations are enables in the console. Check out this msdn demo.
Also i am not shure that your code firs model will work that way. If not try changing your fields with properties.
namespace DataModels
{
public class StoreClient
{
public int Id { get; set; }
public string DisplayName { get; set; }
public StoreClient()
{
}
}
}