ASP中如何从数据库中读取记录.MVC Core使用实体框架Core 1.0
本文关键字:Core 实体 框架 记录 数据库 ASP 读取 MVC | 更新日期: 2023-09-27 18:18:12
我正在使用。net Core 1.0开发简单的MVC 6应用程序,并试图使用实体框架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();
}
不知道我错过了什么!
My Fault发现错误,在override 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");
}
}