实体框架代码首先没有错误,但不能工作



为什么我的代码不起作用?当我尝试运行控制台应用程序时,它总是在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的表并显示消息(All blogs in the database: ASP.NET Blog

抱歉英语不好,请帮助

您的代码清晰明了,但您必须将连接字符串更改为以下格式

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

您错过了连接字符串开头的"@"符号以避免转义字符。

相关内容

最新更新