Pieces
Pieces

Reputation: 2295

Auto Create Database Tables from Objects, Entity Framework

I am trying to do this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part4-cs but instead of using the compact edition of SQL Server I am using a full install on my local machine. The way I read this tutorial is that the Entity Framework is suppose to create the tables from the objects I have defined. My problem is that I keep getting invalid object name dbo.movies, when I run the project. I finally got it to run by creating the table myself so I know the connection string and everything was correct.

My question is, is it possible to generate tables from objects created in C# and if so how?

Upvotes: 15

Views: 65307

Answers (5)

Ronnie
Ronnie

Reputation: 41

ModelContext.Database.EnsureCreated();

Upvotes: 4

Slava Utesinov
Slava Utesinov

Reputation: 13488

You can use FenixRepo library(also available as nuget package) to create particular table, that is a part of you Context. First of all, you should call one time, at startup static Initialize method, where first argument is a factory method, which returns instance of your Context and the second one is an instance of Configuration class. It will prepare SQL scripts for all of your tables, registered at your Context. At case of ASP.NET MVC it is a good decision to paste this code into Global.asax:

FenixRepositoryScriptExtractor.Initialize(() => new Context(), new Configuration());

Then you can create table of desired type MyTable this simple way:

var repo = new FenixRepositoryCreateTable<MyTable>();
//or repo = new FenixRepository<MyTable>();

repo.CreateTable();

Also, if your table spread between several migrations and they have nothing stuff corresponded to other tables, you can specify these migrations(i.e. names of classes from Migrations folder) via FenixAttribute, and exactly they will be used as source of SQL scripts, which will be used for table creation:

[Fenix(nameof(Initial), nameof(MyTableFirstMigration), nameof(MyTableSecondMigration))]
public class MyTable
{
    //some stuff
}

Without this attribute, library will use default scripts. It is always better to specify migrations, because otherwise it is not guaranteed that all indexes will be created and also into your migrations you can include some custom code, that will not be executed at case of default solution.

Library is compatible and tested with EF 6.1.3 at case of MS SQL.

Upvotes: 0

Dismissile
Dismissile

Reputation: 33071

is it possible to generate tables from objects created in C#?

Yes it is possible. Did you happen to create the Database manually in Management Studio before running the Code? That could be your problem. With Code First, the default convention is to create the database if it does not exist already. If the database already exists (even without the tables) then it is going to just use the existing database (but it won't try and create the tables).

You can either delete the database and try and run the code again to see if it will create it for you or put the following line in Global.asax:

Database.SetInitializer(new DropCreateDatabaseAlways<YourDbContextHere>());

Once it has run then I would suggest changing that line to:

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourDbContextHere>());

These namespaces are defined in System.Data.Entity

The DbContext class also exposes a Database property which defines the following useful methods:

Delete()
Create()
CreateIfNotExists()

So if you defined your class like so:

public class MyContext : DbContext {}

You can construct an instance like so:

MyContext db = new MyContext();
db.Database.Delete();
db.Database.Create();

Upvotes: 26

John
John

Reputation: 434

I don't know if this is kosher, but using code-first EF, when I use AddRange, EF will typically create all the tables I've defined. I wanted to keep the database because there are other tables I wanted to keep between application runs. I discovered that the tables would not be re-created after they were deleted if I did not also delete the table EF created called __MigrationHistory.

Once I deleted this table, then EF would re-create the tables without having to re-create the database.

This may not be an advisable approach in production, but for my development needs this resolved my issue. Maybe it will help someone else.

Upvotes: 0

kyjan
kyjan

Reputation: 311

If you create a Linq-to-Sql DataContext you can inject the structure directly into your Database whith:

DbDataContext db = new DbDataContext(connectionString);
db.CreateDatabase();

Upvotes: 0

Related Questions