Entity Framework: generate a specific table if it does not exist?

I have some old tables that I added to the project by reverse engineering to use them as code first .

Something like that:

 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 User table exists, then the Entity Framework does not create other tables, such as the Profile table.

My question is How to specify which table should be created if it does not exist?

+6
source share
2 answers

Have you checked this answer?

EF4 code First create a new table

If you don’t take off and re-create the complete database, I don’t think it is possible.

Setting up an initialization strategy

In the next section, we will begin to change our model, which, in turn, also requires a change in the database schema. There is currently no “turnkey solution" for developing your existing circuit. The development of the database is what we are working on now, and an example of the direction we are heading is given in a recent blog post.

However, it is possible to run some user logic to initialize the database when using context for the first time in AppDomain. This is useful if you want to insert the source data for test runs, but it is also useful to re-create the database if the model has changed. In CTP5, we include a couple of strategies that you can plug in, but you can also write your own.

Add a using statement for System.Data.Entity.Database at the top of Program.cs

 using System.Data.Entity.Database; 

For the pass, we just want to reset and recreate the database whenever the model changes, so the following code is added to the top of the Main method in my Ive program class

 DbDatabase.SetInitializer<ProductContext>( new DropCreateDatabaseIfModelChanges<ProductContext>()); 
+4
source

I had the same problem. And I solved it using the Sql method of the DbMigration class. Something like that

  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"); } } 
+2
source

All Articles