c# - 构造函数无法位于asp net core 5中
问题描述
当我尝试将数据库中的数据输出添加到代码时出现此错误:
InvalidOperationException:找不到适合类型“System.Collections.Generic.IEnumerable`1[cases.Models.Part]”的构造函数。确保类型是具体的,并且公共构造函数的所有参数要么注册为服务,要么作为参数传递。还要确保没有提供无关的参数。
部件.cs
namespace cases.Models
{
public class Part
{
public int Id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string type { get; set; }
}
}
PartDBContext.cs
namespace cases.Models
{
public class PartDBContext : DbContext
{
public string ConnectionString { get; set; }
public PartDBContext(string connectionString)
{
this.ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<Part> GetAllParts()
{
List<Part> list = new List<Part>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("select * from parts", conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Part()
{
Id = Convert.ToInt32(reader["partsid"]),
title = reader["title"].ToString(),
description = reader["description"].ToString(),
type = reader["type"].ToString(),
});
}
}
}
return list;
}
}
}
家庭控制器.cs
namespace cases.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
PartDBContext context = HttpContext.RequestServices.GetService(typeof(PartDBContext)) as PartDBContext;
return View(context.GetAllParts());
}
}
}
启动.cs
namespace cases
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Add(new ServiceDescriptor(typeof(PartDBContext), new PartDBContext(Configuration.GetConnectionString("DefaultConnection"))));
services.AddControllersWithViews();
services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
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.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}
索引.cshtml
@model IEnumerable<cases.Models.Part>
<table class="table">
<tr>
<th>id</th>
<th>title</th>
<th>description</th>
<th>type</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayTextFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.title)
</td>
<td>
@Html.DisplayFor(modelItem => item.description)
</td>
<td>
@Html.DisplayFor(modelItem => item.type)
</td>
</tr>
}
</table>
如何指定构造函数的路径?
解决方案
问题是您如何注册 dbcontext
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
**services.Add(new ServiceDescriptor(typeof(PartDBContext), new PartDBContext(Configuration.GetConnectionString("DefaultConnection"))));**
services.AddControllersWithViews();
services.AddRazorPages();
}
把事情简单化。请用 .net 核心偏好替换 DBContext IoC 注册
services.AddDbContext<VastPayClientContext>((option) =>
{
option.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("PartDBContext"));
option.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
});
推荐阅读
- c# - How do I convert Time(7) to .NET Ticks?
- image-processing - 特征匹配展示
- angularjs - JSON 中位置 4 的意外标记 m - 将字符串从弹簧控制器传递到角度控制器
- api - 如何在 Cloudera Restful API 中使用带有“/”的集群名称
- cqrs - CQRS 和最终一致性
- pandas - 如何从熊猫数据框的两个日期时间列中获取持续时间?
- python-gstreamer - GStreamer Python Playbin 多个视频过滤器
- c# - _layout.cshtml 模板中的动态数据可用于使用此模板的所有页面
- apache-spark - 为什么有些运算符返回 DataFrame 而有些运算符返回 Dataset?
- jquery - 使用 jQuery 调用按钮不会收到 JSON 响应