【发布时间】:2022-01-18 14:46:42
【问题描述】:
在这个平台上开发uname -a:
Linux 5.8.0-63-generic #71-Ubuntu SMP Tue Jul 13 15:59:12 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
并已设置 mysql 数据库:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| test |
+--------------------+
在 Rider IDE 中,asp [核心]:
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ItemsContext": "server=127.0.0.1;user=user;password=password;port=3306;database=test;"
}
}
WebApplication1/Models/Item.cs:
namespace WebApplication1.Models;
public class Item
{
public int Id { get; set; }
public string? Name { get; set; }
public DateTime Due { get; set; }
}
WebApplication1/Data/ItemsContext.cs:
namespace WebApplication1.Data;
public class ItemsContext : DbContext
{
public ItemsContext(DbContextOptions<ItemsContext> options) : base(options)
{
}
public DbSet<Item> Items { get; set; }
}
WebApplication1/program.cs:
using MySqlConnector;
using WebApplication1.Data;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddTransient<MySqlConnection>(_
=> new MySqlConnection(builder.Configuration["ItemsContext"]));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
如果我现在尝试为Item 模型生成剃刀视图,使用以下命令:
dotnet aspnet-codegenerator razorpage -m Item -dc ItemsContext -udl -outDir Pages/Items/ --referenceScriptLibraries
我收到了这个错误:
Building project ...
Finding the generator 'razorpage'...
Running the generator 'razorpage'...
Minimal hosting scenario!
Attempting to compile the application in memory.
Attempting to figure out the EntityFramework metadata for the model and DbContext: 'Item'
Unable to create an object of type 'ItemsContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 StackTrace:
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass21_4.<FindContextTypes>b__13()
所以上面写着Unable to create an object of type 'ItemsContext'我不确定,是因为无法连接mysql,还是什么原因。但是其他都设置好了,怎么解决这个问题呢?
【问题讨论】:
-
您不应该在配置的某个时间点调用 AddDbContext 吗?
MySqlConnection类是什么? -
你知道这些教程没有使用实体框架,对吧?我建议您阅读有关如何执行此操作的正确 EF 文档...
标签: c# asp.net .net-core dbcontext