Entity Framework Code First 在 SQL Server Management Studio 中没有数据库

问题描述 投票:0回答:2

我尝试首先使用 EF 代码创建数据库。 我做了以下事情:

  • 创建了课程
  • 使用所述类创建数据上下文
  • 我在上下文类上使用了无参数构造函数
    :base("connectionstring")
  • 我打开 Nuget Manager 控制台并输入命令:

启用迁移

添加迁移我的数据库

更新数据库

执行此操作后,包含迁移文件的文件夹出现在解决方案资源管理器中,但数据库仍然没有出现在我的 SQL Server Management Studio 中

以下是代码:

1.课程

public class Kid
{      
    public int KidId { get; set; }
    public int Age { get; set; }
    public string Name { get; set; }
}

[Table("School")]
public class School
{
    [Key]
    public int SchoolId { get; set; }
    public string SchoolName { get; set; }
    public List<Kid> Kids { get; set; }

}

public class SchoolContext:DbContext
{
    public  SchoolContext() : base("SchoolContext") { }
    public DbSet<Kid> Kid { get; set; }
    public DbSet<School> School { get; set; }
}

2.主要

class Program
{
    static void Main(string[] args)
    {
        SchoolContext myDb = new SchoolContext();
        Kid mykid = new Kid { Age = 14, KidId = 2, Name = "Adrian" };
        Kid mykid2 = new Kid { Age = 16, KidId = 3, Name = "Adriansan" };
        School mySchool = new School { Kids = new List<Kid>{ mykid, mykid2 }, SchoolId = 73, SchoolName = "Iovan Ducici" };
        myDb.Kid.Add(mykid);
        myDb.School.Add(mySchool);
        myDb.SaveChanges();
        Console.ReadLine();
    }
} 

我怀疑 App.config 文件中需要做一些事情,该文件有一个空的 ConnectionString 标记,但我不知道它必须完成什么。

c# sql-server entity-framework
2个回答
2
投票

通常,您需要在应用程序配置中拥有一个连接字符串,该连接字符串知道您的数据库在“何处”创建。 上下文只是创建数据库的蓝图,“SchoolContext”应该引用应用程序配置中的连接字符串或类似于运行 EF Code First 的实际项目

<connectionStrings>
   <add name="SchoolContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=SchoolContext;Integrated Security=True;"/>
</connectionStrings>

如果您没有这个,它很可能无法工作。 由于您首先使用 EF 代码手动执行了很多操作,因此它可能不会显示。 或者它可能假设 MS 默认数据库以不同于 MS SQL 的方式处理连接,或者它可能是 SQL Express。

我不久前从这个网站上获取了本教程,它对于学习 EF Code First 基础知识的来龙去脉非常有用:http://www.entityframeworktutorial.net/code-first/entity-framework-code-首先.aspx


0
投票

如果您使用的是 .NET Core,请在 appsettings.json 文件中添加以下连接字符串,否则在 app.config 文件中添加连接字符串:

© www.soinside.com 2019 - 2024. All rights reserved.