I have some old tables which I have added them to the project by reverse engineering to use them as code first
.
Something like this:
public class User
{
public string Name { get; set; }
public int Id { get; set; }
}
public class Profile
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public string Name { get; set; }
public virtual User User { get; set; }
}
public class EFDbContext : DbContext
{
public DbSet<User> Users{ get; set; }
public DbSet<Profile> Profiles { get; set; }
}
Here if my old table User
was exist then Entity Framework doesn't create other tables such as Profile
table.
My Question How can I specify which table should be created if doesn't exist?
I had the same problem. And I solved it using the Sql method of the DbMigration class. Something like this
public partial class userToTblUsersMapping : DbMigration
{
public override void Up()
{
this.Sql(@"IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tblUsers]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tblUsers](
[UserID] [varchar](50) NOT NULL,
[UserIDNo] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_tblUsers] PRIMARY KEY CLUSTERED
([UserID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END"
}
public override void Down()
{
DropTable("dbo.tblUsers");
}
}
Have you checked this answer?
EF4 Code First create new table
Unless you drop and re-created you full database, I don't think it's possible.
Setting an Initialization Strategy
In the next section we are going to start changing our model which in turn means the database schema needs to change as well. Currently there is no ‘out of the box’ solution to evolve your existing schema in place. Database evolution is something we are currently working on and a sample of the direction we are heading is provided in a recent design blog post.
There is however the opportunity to run some custom logic to initialize the database the first time a context is used in an AppDomain. This is handy if you want to insert seed data for test runs but it’s also useful to re-create the database if the model has changed. In CTP5 we include a couple of strategies you can plug in but you can also write custom ones.
Add a using statement for System.Data.Entity.Database at the top of Program.cs
using System.Data.Entity.Database;
For the walkthrough we just want to drop and re-create the database whenever the model has changed, so at the top of the Main method in my Program class I’ve added the following code
DbDatabase.SetInitializer<ProductContext>(
new DropCreateDatabaseIfModelChanges<ProductContext>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With