为什么我的代码不起作用?
当我尝试运行控制台应用程序时,它总是停在db.Blogs.Add(blog)
上,永远不会继续。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace CodeFirstNewDatabaseSample
{
class Program
{
static void Main(string[] args)
{
using(var db = new BloggingContext())
{
Console.Write("Enter the name of new Blog:");
var name = Console.ReadLine();
var blog = new Blog { Name = name };
db.Blogs.Add(blog); //Stop working here but no error.
db.SaveChanges();
var query = from b in db.Blogs
orderby b.Name
select b;
Console.WriteLine("All blogs in the database:");
foreach (var item in query)
{
Console.Write(item.Name);
}
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Post { 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 BloggingContext : DbContext
{
public BloggingContext()
: base("Data Source=(localdb)\v11.0;Initial Catalog=CodeFirstNewDatabaseSample.BloggingContext;Integrated Security=True")
{
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
}
当我输入ASP.NET Blog
并按下输入时,没有任何反应。
它应该创建一个包含2个名为Blog
和Post
的表的新数据库
并显示消息(All blogs in the database: ASP.NET Blog
)
抱歉英文不好,请帮忙
答案 0 :(得分:2)
您的代码清晰明了,但您必须将连接字符串更改为以下格式
public class BloggingContext : DbContext
{
public BloggingContext()
: base(@"Data Source=(localdb)\v11.0;Initial Catalog=CodeFirstNewDatabaseSample.BloggingContext;Integrated Security=True")
{
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
你错过了&#34; @&#34;在连接字符串的开头签名以避免转义字符。