繁体   English   中英

如何使用实体框架核心1.0从ASP.MVC核心的数据库中读取记录

[英]How to Read Record From Database in ASP.MVC Core using Entity Framework Core 1.0

我正在使用.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");
    }
}

启动文件

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM