c# - Ef Core:添加迁移失败没有无参数构造函数定义错误

我只是尝试从代码迁移数据库,但收到此错误

无法动态创建“KurumsalWebCoreEntity.Fotograflar”类型的实例。原因:未定义无参数构造函数。

我当我评论这个构造函数时,错误消失了,但是我不明白如何在没有评论构造函数的情况下修复它。

我使用 SQL Server 作为数据库,并使用 Entity Framework 6.0.1 版本。

谢谢你的帮助

摄影.cs

using KurumsalWebCoreEntity.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Security.Cryptography;
using System.Text;

namespace KurumsalWebCoreEntity
{
   
    public partial class Fotograflar : BaseEntity
    {
        public Fotograflar(byte[] file, int urunId)
        {
            UrunId = urunId;
            Hash = ComputeSha256Hash(file);
            Fotograf = file;
        }
        [Required, DataType("image")]
        [Display(Name = "Fotoğraf")]
        public byte[] Fotograf { get; set; }       
        public string Hash { get; set; }
        public int UrunId { get; set; }

       
      
        [ForeignKey("UrunId")]
        public virtual ICollection<Urunler> Urunler { get; set; }

        public virtual ICollection<Varyasyonlar> Varyasyonlar { get; set; }
        public override void Build(ModelBuilder builder)
        {
            builder.Entity<Siparisler>(entity =>
            {

            });
        }

        public string ComputeSha256Hash(byte[] rawData)
        {
            // Create a SHA256   
            using (SHA256 sha256Hash = SHA256.Create())
            {
                // ComputeHash - returns byte array  
                byte[] bytes = sha256Hash.ComputeHash(rawData);

                // Convert byte array to a string   
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < bytes.Length; i++)
                {
                    builder.Append(bytes[i].ToString("x2"));
                }
                return builder.ToString();
            }
        }
    }
}

AppDbContext.cs

using KurumsalWebCoreEntity.Infrastructure;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using System.Reflection;

namespace KurumsalWebCoreEntity
{
    public class AppDbContext : IdentityDbContext<AppUser, AppRole, int>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
        {
        }

        public AppDbContext()
        {

        }
      
        protected override void OnModelCreating(ModelBuilder builder)
        {

            Assembly
                   .GetExecutingAssembly()
                   .GetTypes()
                   .Where(p => !p.IsAbstract && p.GetInterfaces().Any(q => q.Name == nameof(IBaseEntity)))
                   .ToList()
                   .ForEach(p => p.GetMethod(nameof(IBaseEntity.Build)).Invoke(Activator.CreateInstance(p), new[] { builder }));

            base.OnModelCreating(builder);


        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();

            var provider = configuration["Application:DatabaseProvider"];


            if (provider == "SqlServer")
            {
                optionsBuilder.UseSqlServer(configuration.GetConnectionString("SqlServer"));
                optionsBuilder.UseLazyLoadingProxies();
            }
            else
            {
                optionsBuilder.UseMySql(configuration.GetConnectionString("Mysql"), ServerVersion.AutoDetect(configuration.GetConnectionString("Mysql")));
                optionsBuilder.UseLazyLoadingProxies();
            }

        }

        public virtual DbSet<Urunler> Urunler { get; set; }
        public virtual DbSet<Fotograflar> Fotograflar { get; set; }
        public virtual DbSet<Varyasyonlar> Varyasyonlar { get; set; }
        public virtual DbSet<SiparisDurumlari> SiparisDurumlari { get; set; }
        public virtual DbSet<Siparisler> Siparisler { get; set; }
        public virtual DbSet<Ayarlar> Ayarlar { get; set; }
    }
}

程序.cs

using KurumsalWebCoreEntity;
using KurumsalWebCoreHelper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Quartz;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Trias.Code.Job;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();

builder.Services.AddDbContext<AppDbContext>(options =>
{
    switch (builder.Configuration.GetValue<string>("Application:DatabaseProvider"))
    {
        case "Mysql":
            options.UseMySql(
            builder.Configuration.GetConnectionString("Mysql"),
            ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("Mysql")),
            config =>
            {
                config.MigrationsAssembly("KurumsalWebCoreMigrationMysql");

            }).UseLazyLoadingProxies();
            break;
        case "SqlServer":
        default:
            options.UseSqlServer(
                builder.Configuration.GetConnectionString("SqlServer"),
                config =>
                {
                    config.MigrationsAssembly("KurumsalWebCoreMigrationSqlServer");
                }).UseLazyLoadingProxies();
            break;
    }
});

builder.Services.AddIdentity<AppUser, AppRole>(opt =>
{
    opt.User.RequireUniqueEmail = true;
    opt.User.AllowedUserNameCharacters = "abcçdefgğhıijklmnoöpqrsştuüvwxyzABCÇDEFGHIİJKLMNOÖPQRŞSTUÜVWXYZ0123456789-._";

    opt.Password.RequiredLength = 6;
    opt.Password.RequireNonAlphanumeric = false;
    opt.Password.RequireLowercase = false;
    opt.Password.RequireUppercase = false;
    opt.Password.RequireDigit = false;
}).AddPasswordValidator<CustomPasswordValidator>().

AddEntityFrameworkStores<AppDbContext>().
AddUserValidator<CustomUserValidator>().
AddErrorDescriber<CustomIdentityErrorDescriber>().
AddDefaultTokenProviders();

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = "AccountCookie";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromDays(7);
    options.LoginPath = new PathString("/Admin/Account/GirisYap");
    options.LogoutPath = new PathString("/Admin/Account/CikisYap");
    options.AccessDeniedPath = new PathString("/Admin/Account/AccessDenied");
});

AppDbContext db = new();

builder.Services.AddLocalization(opt => { opt.ResourcesPath = "Resources"; });

builder.Services.AddAuthorization();

builder.Services.AddControllersWithViews()
.AddNewtonsoftJson(option =>
{
    option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});
builder.Services.AddControllers().AddViewLocalization();

builder.Services.AddControllers().AddNewtonsoftJson();

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

builder.Services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();

IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());

builder.Services.AddSingleton<IFileProvider>(physicalProvider);

builder.Services.AddDistributedMemoryCache();

#region Fiyat Kaydederken hata almamak için fiyattaki virgülü nokta ile değiştiriyor

builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-GB");
    options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-GB") };
    options.RequestCultureProviders.Clear();
});

#endregion Fiyat Kaydederken hata almamak için fiyattaki virgülü nokta ile değiştiriyor

builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
});

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddResponsiveFileManager(options =>
{
    //
    options.MaxSizeUpload = 32;
});

builder.Services.AddQuartz(q =>
{
    q.ScheduleJob<JobSiparis>(TJobSiparis => TJobSiparis
        .WithIdentity("TJobSiparis")
        .StartNow()
        .WithDailyTimeIntervalSchedule(x => x.WithInterval(55, IntervalUnit.Second))
        .WithDescription("TJobSiparis")
    );
});

//ASP.NET Core hosting
builder.Services.AddQuartzServer(options =>
{
    // when shutting down we want jobs to complete gracefully
    options.WaitForJobsToComplete = true;
});


var app = builder.Build();



if (!app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();  
}
else
{
    app.UseExceptionHandler("/gfgfgf/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();

    //HTTPS YE YÖNLENDİRMEK İÇİN AŞAĞIDAKİ KODLARI AKTİF ET

    //var options = new RewriteOptions();
    //options.AddRedirectToHttps();
    //options.Rules.Add(new RedirectToWwwRule());
    //app.UseRewriter(options);
}

app.UseHttpsRedirection();

app.UseSession();

app.UseDefaultFiles();
app.UseStaticFiles(); // shortcut for HostEnvironment.WebRootFileProvider

app.UseResponsiveFileManager();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseCookiePolicy();

app.UseEndpoints(endpoints =>
{
    endpoints.MapAreaControllerRoute(
       name: "hjhjhjh",
       areaName: "jhjhjh",
       pattern: "jhjhjh/{controller=Home}/{action=jhjhjhj}/{id?}");

    endpoints.MapControllerRoute(
        name: "areas",
        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

    endpoints.MapControllerRoute(
    name: "home",
    pattern: "/{controller=Home}/{action=jhjhjh}/{id?}");

    endpoints.MapControllerRoute(
    name: "urlseoredirect",
    pattern: "{url?}/{controller=UrlSeo}/{action=jhjhj}");
});
app.Run();

回答1

请使用 AddDbContextFactory 在应用程序的依赖注入 (D.I.) 容器中注册用于创建 DbContext 实例的工厂。它将解决此问题。

相关文章:

https://stackoverflow.com/a/43509910/7687666

您可以阅读以下博客以了解如何使用 IDbContextFactory

https://morioh.com/p/14b0b4eedb59

相似文章

最新文章