2014-09-06 95 views
1

为什么我的代码不工作? 当我尝试运行控制台应用程序时,它总是停止在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和压入没有什么发生。 应该创建一个名为BlogPost 2台新的数据库并显示消息(All blogs in the database: ASP.NET Blog

对不起,我英文不好,请大家帮

+0

@YuliamChandra是的,我做到了,但仍然没有错误显示。 – 2014-09-06 05:09:28

+0

对不起,我错过了评论的代码,它是否仍在'db.Blogs.Add(blog);'行上运行或立即关闭?如果还在等待,直到发生什么事情.. – 2014-09-06 05:10:56

+0

@YuliamChandra我等了10分钟仍然没有工作,你可以尝试我的代码。 – 2014-09-06 05:33:49

回答

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; } 
} 

您错过连接字符串开始处的“@”符号以避免转义字符。

相关问题