DbContext.Add在我的电脑上失败,但在另一台电脑上有效

本文关键字:电脑 有效 一台 我的 Add 失败 DbContext | 更新日期: 2023-09-27 18:30:14

ATM我尝试学习如何使用数据库。现在我想使用实体框架。我做了这个简单的示例,但它在我的电脑上不起作用。它总是在数据库上崩溃。博客。添加(博客);但它不会抛出错误或其他任何东西。我把代码交给了我的一个朋友,他也在编程,如果他运行代码,它对他有效。

class Program
{
    static void Main(string[] args)
    {
        using (var db = new BloggingContext())
        {
            // Create and save a new Blog 
            Console.Write("Enter a name for a new Blog: ");
            var name = Console.ReadLine();
            var blog = new Blog { Name = name };
            db.Blogs.Add(blog);
            db.SaveChanges();
            // Display all Blogs from the database 
            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.WriteLine(item.Name);
            }
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
    } 
}
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 BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

我不知道为什么它不起作用,希望有人能帮助我。

问候

Schlinger

DbContext.Add在我的电脑上失败,但在另一台电脑上有效

检查你的app.config。EF部分应该看起来像

<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
  <parameters>
    <parameter value="mssqllocaldb" />
  </parameters>
</defaultConnectionFactory>
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>