代码优先模型 - 无法生成数据库

时间:2014-01-19 18:14:04

标签: c# entity-framework ef-code-first

我将尝试使用CodeFirst模型来创建dataBase。

准备如下代码(来自online tutorial)。代码与教程完全相同:

class Program
{
    static void Main(string[] args)
    {
        using (BlogContext db = new BlogContext())
        {
            Console.Write("Enter a name for a new Blog:");
            var name = Console.ReadLine();

            var blog = new Blog { Name = name };
            Database.SetInitializer<BlogContext>(null);
            db.Blogs.Add(blog);
            db.SaveChanges();

            var query = from b in db.Blogs
                        orderby b.Name
                        select b;

            foreach (var item in query)
            {
                Console.WriteLine(item.Name);
            }

        }
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Name { get; set; }

    public virtual List<Post> Posts { get; set; }

}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

结果 - 得到了异常

enter image description here

找到此异常的解决方案here。现在没关系,工作并向我显示已保存的数据,但在我的Sql Server对象资源管理器中,我看不到任何数据库或表。

enter image description here

有什么建议吗? Wnat我必须做修复这个吗?


修改

enter image description here

因此,正如@Sergiy Berezovskiy所提到的那样 - 我尝试检查dataBase并手动添加dataConnection以显示刚创建的数据库。

enter image description here

1 个答案:

答案 0 :(得分:2)

我认为你有两个问题:

  • 您正在查找错误的数据库。如果没有指定连接字符串,Entity Framework将在本地SQLEXPRESS服务器上创建数据库,其名称等于上下文名称 - SomeNamespace.BlogContext
  • 您在创建数据库后更改了模型。这就是你看到错误的原因。使用Code First Migrations更新现有数据库,或使用DropCreateDatabaseWhenModelChanges数据库初始化程序重新创建数据库。