首页 > 解决方案 > 构造函数无法位于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>

如何指定构造函数的路径?

标签: c#asp.net-core

解决方案


问题是您如何注册 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);
            });

推荐阅读