![](/img/trans.png)
[英]Can't create database with Entity Framework code-first + no database
[英]Entity Framework code-first doesn't create database
我正在嘗試使用Entity Framework中的代碼優先功能來生成數據庫,但是它不起作用。 這是控制台應用程序的app.config
中的連接字符串:
<add name="BlogDbContext"
connectionString="data source=myserver; initial catalog=CodeFirstDemo; integrated security=SSPI"
providerName="System.Data.SqlClient" />
這是我的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)
{
}
}
}
在包管理器控制台中,我嘗試過: enable-migration
,然后add-migration
,然后update-database
..但什么都沒發生。
我嘗試了像這樣的其他問題中建議的連接字符串:
<add name="CodeFirstDemo.BlogDbContext"
connectionString="data source=myserver; initial catalog=CodeFirstDemo; integrated security=SSPI"
providerName="System.Data.SqlClient" />
有任何想法嗎?
添加具有以下簽名的空構造函數,以引用您已添加到app.config的連接字符串:
public BlogDbContext()
: base("Name=BlogDbContext")
{
}
您無需使用遷移即可創建數據庫。您可以按照以下Main
方法執行以下操作:
using (var context = new BlogDbContext())
{
context.Database.CreateIfNotExists();
}
由於您使用的是代碼優先的代碼,因此應該具有類似於以下示例的代碼:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>().ToTable("Post");
base.OnModelCreating(modelBuilder);
}
這些將創建您實體的數據庫表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.