我无法在EntityFramework Core中创建简单的数据库

时间:2017-12-06 14:52:25

标签: entity-framework-core

我是EntityFramework和Core的新手。

我想在EntityFramework Core 2.0中创建一个简单的数据库。该项目是一个ConsoleApplication,我将它包含在Nuget包中的Microsoft.AspNetCore.All中。这是一个代码:

namespace TestEF
{
class Program
{
    static void Main(string[] args)
    {
        string connStr = "Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";

        var db = new SchoolContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connStr).Options);
        db.Students.Add(
            new Student()
            {
                LastName = "Miranda",
                EnrollmentDate = DateTime.Now,
                FirstMidName = "Guillermo"
            });
        db.SaveChanges();

        Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions options) : base(options)
    {
    }
    public DbSet<Student> Students { get; set; }
}
}

我以用户名&#34; gmiranda&#34;登录到内部网。当我运行项目时,我收到以下消息错误:

发生了System.Data.SqlClient.SqlException   的HResult = 0x80131904   Message =无法打开数据库&#34; SchoolDataBase&#34;登录请求。登录失败。 用户&#39; domain \ gmiranda&#39;。

登录失败

我做错了什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

您应该尝试以下代码:

class Program
{
    static void Main(string[] args)
    {
        string connStr = "Data Source=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";

        var db = new SchoolContext();
        db.Students.Add(
            new Student()
            {
                LastName = "Miranda",
                EnrollmentDate = DateTime.Now,
                FirstMidName = "Guillermo"
            });
        db.SaveChanges();

        Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

public class SchoolContext : DbContext
{
    public SchoolContext() : base()
    {

    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true");
    }
    public DbSet<Student> Students { get; set; }
}

然后打开Package Manager Console并使用命令Add-Migration FirstMigrarion。 它使用名称FirsMigration添加到数据库的迁移。 然后使用命令Update-Database。 然后运行你的程序。

尝试使用本教程:https://docs.microsoft.com/en-us/ef/core/get-started/full-dotnet/new-db