Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 766
Pieces Avatar asked Mar 26 '12 14:03

Pieces


People also ask

Can Entity Framework Create database?

However, with ASP.NET you can use Entity Framework to generate a database based on an object model. Generally you would create an ER diagram and manually create all the tables one by one. With Entity Framework, you can create your entities in Visual Studio and all your tables will be created for you.

Does EF core create database if not exist?

Entity Framework automatically creates database when it doesn't exist.

What is database Setinitializer?

The database initializer is called when a the given DbContext type is used to access a database for the first time. The default strategy for Code First contexts is an instance of CreateDatabaseIfNotExists<TContext>. C# Copy.


2 Answers

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();
like image 125
Dismissile Avatar answered Nov 04 '22 00:11

Dismissile


ModelContext.Database.EnsureCreated();
like image 3
Ronnie Avatar answered Nov 04 '22 02:11

Ronnie