从对象自动创建数据库表,实体框架 [英] Auto Create Database Tables from Objects, Entity Framework

查看:220
本文介绍了从对象自动创建数据库表,实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试本教程 http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/getting-started-with-mvc3-part4-cs ,而不是使用SQL Server的紧凑版本我正在本地机器上完全安装。我阅读本教程的方式是,实体框架是假设从我定义的对象创建表。我的问题是,当我运行项目时,我继续获取无效的对象名称dbo.movi​​es。我终于可以通过自己创建表来运行,所以我知道连接字符串,一切都正确。

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.

我的问题是,是否可以从创建的对象生成表在C#中,如果是这样?

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

推荐答案


是否可以从C# ?

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

是的,这是可能的。在运行代码之前碰巧在Management Studio中手动创建数据库?这可能是你的问题。使用Code First,默认约定是创建数据库(如果不存在)。如果数据库已经存在(即使没有表),那么它只是使用现有的数据库(但不会尝试创建表)。

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).

你可以删除数据库并再次尝试运行代码,看看它是否为您创建或在Global.asax中放置以下行:

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

这些命名空间在 System.Data.Entity

DbContext 类还暴露了一个Database属性,它定义了以下有用的方法:

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

这篇关于从对象自动创建数据库表,实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆