[英]Entity Framework code-first doesn't create database
I am trying to use code-first in Entity Framework to generate the database, but it's not working. 我正在尝试使用Entity Framework中的代码优先功能来生成数据库,但是它不起作用。 Here's my connection string in the
app.config
of the console application: 这是控制台应用程序的
app.config
中的连接字符串:
<add name="BlogDbContext"
connectionString="data source=myserver; initial catalog=CodeFirstDemo; integrated security=SSPI"
providerName="System.Data.SqlClient" />
and here's my program.cs
file code: 这是我的
program.cs
文件代码:
using System.Data.Entity;
namespace CodeFirstDemo
{
public class Post
{
public int PostId { get; set; }
public System.DateTime DatePublished { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
public class BlogDbContext : DbContext
{
public DbSet<Post> Posts { get; set; }
}
class Program
{
static void Main(string[] args)
{
}
}
}
In package manager console I tried: enable-migration
, then add-migration
, then update-database
.. but nothing happened. 在包管理器控制台中,我尝试过:
enable-migration
,然后add-migration
,然后update-database
..但什么都没发生。
I tried connection string as suggested in other questions like this: 我尝试了像这样的其他问题中建议的连接字符串:
<add name="CodeFirstDemo.BlogDbContext"
connectionString="data source=myserver; initial catalog=CodeFirstDemo; integrated security=SSPI"
providerName="System.Data.SqlClient" />
Any ideas? 有任何想法吗?
Add an empty constructor with the following signature to reference the connection string you already added to your app.config: 添加具有以下签名的空构造函数,以引用您已添加到app.config的连接字符串:
public BlogDbContext()
: base("Name=BlogDbContext")
{
}
You don't need to use migration to create your database.You can do what I show below in your Main
method: 您无需使用迁移即可创建数据库。您可以按照以下
Main
方法执行以下操作:
using (var context = new BlogDbContext())
{
context.Database.CreateIfNotExists();
}
Since you are using code-first you should have these codes that look alike to the following example : 由于您使用的是代码优先的代码,因此应该具有类似于以下示例的代码:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>().ToTable("Post");
base.OnModelCreating(modelBuilder);
}
These will create the database table of your entities. 这些将创建您实体的数据库表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.