Entity Framework 7 Update DbContext after migration - c#

I've got an existing DB and new WPF project.
1) I scaffolded db context with Scaffold-DbContext and recieved DbContext.cs and a file for each entity that represents a DB tables. That's OK.
Here is example of one of them:
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
}
2) I've manually updated this entity (no changes in DbContext.cs) :
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
public string SomeString { get; set; }
}
3) I've used Add-Migration command. Now I've got a migration file that describes required changes and DbContextSnapshot.cs. Snapshot includes changes I've just made with SomeEntity. Database is not updated.
4) I've used Update-Database command. Database updated to match last migration. But my DbContext.cs doesn't know anything about changes in DB. It is still the same old good DbContext that I had after scaffolding DB.
Is this OK? Should I now change DbContext manually to match changes that I've made to my entities and applied them to DB? Is there a way to update DbContext.cs from DB after changes without 'rescaffolding'? (Because, for example, all comments and attributes in entity files will be lost, because they will be replaced with new ones if I use Scaffold-DbContext again)

You will have to run scaffolding again, but keep in mind that the generated classes are partial, so you can put your changes in another file

Related

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.

Entity Framework invalid object name "dbo.EA_EmployeePerformance"

It is weird since I use the simple membership initialization my EF model cannot create a new table. My code was able to create the new table needed if there is a transaction required for the model.
This is my model :
public class EmployeeDBContext : DbContext
{
public EmployeeDBContext()
: base("DefaultConnection")
{
Database.SetInitializer<EmployeeDBContext>(new CreateDatabaseIfNotExists<EmployeeDBContext>());
}
public DbSet<EA_Employee> Employees { get; set; }
public DbSet<EA_EmployeePerformance> EmployeePerformances { get; set; }
public DbSet<EA_EmployeeRank> EmployeeRanks { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
[Table("EA_EmployeePerformance")]
public class EA_EmployeePerformance
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[Display(Name = "Employee Performance Id")]
public int EmployeePerformanceId { get; set; }
[Index("Performance", IsUnique = true)]
[MaxLength(20)]
[Required]
public string Performance { get; set; }
public EA_EmployeePerformance()
{
Performance = "";
}
}
Whenever I SaveChanges(), the DB throws me
"Invalid object name dbo.EmployeePerformance".
I check the database and the database only contains tables required from simple membership.
How can I auto create the tables when a transaction is occurred for that model?
--------- EDITED ---------
Now I know what is my problem. The problem is because I use multiple dbContext in one database. It is gonna be tricky to do the migration because migration only works on one dbContext isn't it?
So in my case the problem is because the original AccountDBContext from the simple membership is taking over my database, that is why my other dbContext such as the EmployeeDBContext cannot create the new table (please correct me if i'm wrong).
Is there a way for me to keep the multiple dbContexts in a single database?
First you have to change your Db Initializer to DropCreateDatabaseIfModelChanges otherwise, you will still have the old database and you will never get the model changes without deleting the database manually.
database. It is gonna be tricky to do the migration because migration only works on one dbContext isn't it?
For migration I recommend you to create one DbContext for migration that called for Example MigrationDbContext which contains the the all DbSets and the POCO objects, also when the POCO objects belong to other assembly then just reference them.
Try using Migrations, this will help you manage your changes in your code and update the database scheme accordingly.
Here is a guide for how to use it Migrations.

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.

Set up database creation/migrations from code for Entity Framework 6 + MySQL

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()
{
}
}
}

Code First Entity Framework not building database

I am trying to implement Entity Framework using code first but it is not building the database tables. I'm not sure what i'm doing wrong. I am using this tutorial -http://msdn.microsoft.com/en-us/data/jj193542 but I am trying to use it with a web application instead of a console application. I created a Models folder and put my context class in that folder. Here is my dbcontext code:
namespace GroceryAssistant.Model
{
public class GroceryShopperContext : DbContext
{
public DbSet<List> Lists { get; set; }
public DbSet<ListItem> ListItems { get; set; }
public DbSet<User> User { get; set; }
}
}
I created put the connection string in the web.release.config and the web.debug.config files. I'm not sure what else I have to do. Where should i put my DbContext code so that the tables will be created?
If you do not change the default behavior, the first time you use the DbContext it will create your database.

Categories