我只是尝试从代码迁移数据库,但我得到这个错误
无法动态创建类型为'KurumsalWebCoreEntity.Fotograflar'的实例。原因:没有定义无参数构造函数。
当我注释这个构造函数时,错误消失了,但是,我不明白如何在没有注释构造函数的情况下修复它。
我使用SQL Server作为数据库,使用实体框架6.0.1版本。
感谢您的帮助
Fotograflar.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; }
}
}
Program.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();
请使用AddDbContextFactory
注册一个工厂,用于在应用程序的依赖注入(di)容器中创建DbContext实例。它会解决这个问题。
相关文章:
实体框架核心:不能添加迁移:无参数构造函数
你可以阅读下面的博客来学习如何使用IDbContextFactory
。
宣布实体框架Core EF Core 5.0预览7 |。net博客