问题
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?
回答1:
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.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/36916150/table-not-mapped-using-ef-code-first-approach