Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
538 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...