Blazi Blazi - 20 days ago 7
ASP.NET (C#) Question

Entity Framework: Generating specific table if doesn't exist?

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?

Answer

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>());