如何使用Entity Framework Core 1.0從ASP.MVC Core中的數據庫讀取記錄

asp.net-core-mvc c# entity-framework-core sql-server-2014

我正在使用.NET Core 1.0開發簡單的MVC 6應用程序並嘗試使用Entity Framework Core 1.0從數據庫中讀取數據,並在我嘗試讀取表的LINQ查詢中收到以下錯誤; LINQ查詢位於HomeController類中

錯誤

An unhandled exception occurred while processing the request.
SqlException: Invalid object name 'TestModel'.

模型類

[Table("TestTable")]
public class TestModel
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
}

TestDbContext

public class TestDbContext: DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options): base(options)
    { }

    public DbSet<TestModel> TestModels { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestModel>().ToTable("TestModel");
    }
}

Startup.cs

   public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);


        services.AddDbContext<TestDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("UCASAppDatabase")));


        services.AddMvc();
    }

project.json

"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"System.ComponentModel.Annotations": "4.1.0"

appsettings.json

{
"ApplicationInsights": {
"InstrumentationKey": ""
},
"Logging": {
 "IncludeScopes": false,
 "LogLevel": {
  "Default": "Debug",
  "System": "Information",
  "Microsoft": "Information"
 }
 },
 "ConnectionStrings": {
  "UCASAppDatabase": "Data Source=mydb;Initial Catalog=UCAS-DB;Integrated Security=True;Persist Security Info=True"
 }
}

HomeController(試圖在這裡讀表!)

 public class HomeController : Controller
{
    private readonly TestDbContext _context;
    public HomeController(TestDbContext context)
    {
        this._context = context;
    }

  public IActionResult About()
    {
            var query = (from b in _context.TestModels
                         select b).ToList();

            ViewData["Message"] = "Your application description page.";

        return View();
    }

不知道我在這裡錯過了什麼!

一般承認的答案

我的錯誤發現錯誤,在覆蓋OnModelCreating時給出了錯誤的表名

public class TestDbContext: DbContext
{
    public TestDbContext(DbContextOptions<TestDbContext> options): base(options)
    { }

    public DbSet<TestModel> TestModels { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestModel>().ToTable("TestTable");
    }
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow