Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 未找到实体类型MyImage的合适构造函数_C#_.net_Asp.net Core_Entity Framework Core - Fatal编程技术网

C# 未找到实体类型MyImage的合适构造函数

C# 未找到实体类型MyImage的合适构造函数,c#,.net,asp.net-core,entity-framework-core,C#,.net,Asp.net Core,Entity Framework Core,我得到一个例外: System.InvalidOperationException异常 HResult=0x80131509 消息=未找到实体类型“MyImage”的合适构造函数。以下构造函数的参数无法绑定到实体类型的属性:无法绑定“MyImage(字符串名称、字符串国家/地区、图像图像)”中的“image”。 Source=Microsoft.EntityFrameworkCore 堆栈跟踪: 位于Microsoft.EntityFrameworkCore.Metadata.Conventio

我得到一个例外:

System.InvalidOperationException异常 HResult=0x80131509 消息=未找到实体类型“MyImage”的合适构造函数。以下构造函数的参数无法绑定到实体类型的属性:无法绑定“MyImage(字符串名称、字符串国家/地区、图像图像)”中的“image”。 Source=Microsoft.EntityFrameworkCore 堆栈跟踪: 位于Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConstructorBindingConvention.Apply(InternalModelBuilder modelBuilder) 在Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)中 在Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)中 在Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()中 在Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()中 位于Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext上下文、IConventionSetBuilder约定SetBuilder、IModelValidator验证器) 在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.c__DisplayClass5_0.b__1()中 在System.Lazy
1.ViaFactory(LazyThreadSafetyMode模式)
在System.Lazy
1.ExecutionAndPublication(LazyHelper ExecutionAndPublication,布尔值useDefaultConstructor) 在System.Lazy
1.CreateValue()中
位于Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext上下文、IConventionSetBuilder约定SetBuilder、IModelValidator验证器)
在Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()中
在Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()中
位于Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.c.b_uu7_u2(IServiceProvider p)
位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite FactoryCallSite,ServiceProviderEngineScope作用域)
位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,Target参数) 位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite ScopedCallSite,ServiceProviderEngineScope范围) 位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,Target参数)
位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite ConstructorCallSite,ServiceProviderEngineScope作用域)
位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,Target参数) 位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite ScopedCallSite,ServiceProviderEngineScope范围) 位于Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor
2.VisitCallSite(IServiceCallSite callSite,Target参数)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.c__DisplayClass1_0.b__0(ServiceProviderEngineScope作用域)
在Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(输入serviceType,ServiceProviderEngineScope ServiceProviderEngineScope)
位于Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(类型serviceType)
位于Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider提供程序,键入serviceType)
位于Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider提供程序)
在Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()中
在Microsoft.EntityFrameworkCore.DbContext.get\u InternalServiceProvider()中
在Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure.get_Instance()中
在Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.Microsoft.EntityFrameworkCore.Infrastructure.IIinfrastructure.get_Instance()中
位于Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure
1访问器) 位于Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1访问器) 在Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_DatabaseCreator()中 在Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsurereDeleted()中 在D:\School\webapplications IV\digitalizedapi\digitalizedapi\digitalizedapi\Data\DataInitializer.cs中的digitalizedapi.Data.dataInitializedata()处:第27行 在D:\School\WebApplications IV\DigitalizedAPI\DigitalizedAPI\DigitalizedAPI\DigitalizedAPI\Startup.cs中的DigitalizedAPI.Startup.Configure(IApplicationBuilder应用程序、IHostingEnvironment环境、DataInitializer DataInitializer)中进行配置:第103行

我不知道原因是什么

数据库上下文 配置 这是配置
公共类ImageVisitorConfiguration:IEntityTypeConfiguration{
公共void配置(EntityTypeBuilder){
HasKey(i=>new{i.ImageId,i.VisitorId});
builder.HasOne(i=>i.Visitor)
.有很多(v=>v.Liked)
.HasForeignKey(i=>i.VisitorId);
builder.HasOne(i=>i.Image)
.有很多
.HasForeignKey(i=>i.ImageId);
}
}
最后

启动
公共类启动{
公共启动(IConfiguration配置){
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
公共空间公司
    public class ApplicationDbContext : IdentityDbContext {

    public DbSet<MyImage> Images { get; set; }
    public DbSet<Visitor> Visitors { get; set; }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options) {
    }

    protected override void OnModelCreating(ModelBuilder builder) {
        base.OnModelCreating(builder);
        builder.ApplyConfiguration(new ImageConfiguration());
        builder.ApplyConfiguration(new VisitorConfiguration());
        builder.ApplyConfiguration(new ImageVisitorConfiguration());
    }
}
        private readonly ApplicationDbContext _dbContext;
    private readonly UserManager<IdentityUser> _userManager;
    private readonly IImageRepository _imageRepository;

    public DataInitializer(ApplicationDbContext context, UserManager<IdentityUser> userManager, IImageRepository imageRepository) {
        _dbContext = context;
        _userManager = userManager;
        _imageRepository = imageRepository;
    }

    //public async Task InitializeData() {
    //    _dbContext.Database.EnsureDeleted();
    //    if (_dbContext.Database.EnsureCreated()) {
    //    }
    //}

    public void InitializeData() {
        _dbContext.Database.EnsureDeleted();//error gets thrown here
        if (_dbContext.Database.EnsureCreated()) {
            //MyImage image1 = new MyImage("Parallax1","France",Image.FromFile("DSC_2544c2.jpg"));
            //_imageRepository.Add(image1);

            _imageRepository.SaveChanges();



        }
    }

    private async Task CreateUser(string email, string password) {
        var user = new IdentityUser { UserName = email, Email = email };
        await _userManager.CreateAsync(user, password);
    }
}
    public class MyImage {

    #region Fields
    private string _name;
    #endregion

    #region Properties
    public int Id { get; set; }
    [Required]
    public string Name {
        get {
            return _name;
        }

        set {
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) {
                throw new ArgumentException("Name cannot be empty.");
            }
            _name = value;
        }
    }
    public int ISO { get; set; }
    public double ShutterSpeed { get; set; }
    public double Aperture { get; set; }
    public string Country { get; set; }
    public string Content { get; set; }
    #endregion

    #region Constructor
    //public MyImage(string name, int iso, double shutterspeed, double aperture, string country, string content) {
    //    Name = name;
    //    ISO = iso;
    //    ShutterSpeed = shutterspeed;
    //    Aperture = aperture;
    //    Country = country;
    //    Content = content;

    //}

    public MyImage(string name, string country, Image image) {
        Name = name;
        ISO = Convert.ToInt32(Encoding.UTF8.GetString(image.GetPropertyItem(0x8828).Value));
        ShutterSpeed = Convert.ToInt64(Encoding.UTF8.GetString(image.GetPropertyItem(0x9201).Value));
        Aperture = Convert.ToInt32(Encoding.UTF8.GetString(image.GetPropertyItem(0x9202).Value)); ;
        Country = country;
        Content = ConvertImage(image);

    }
    #endregion

    #region Methods
    private string ConvertImage(Image imageToConvert) {
        byte[] Ret;
        try {
            using (MemoryStream ms = new MemoryStream()) {
                imageToConvert.Save(ms, imageToConvert.RawFormat);
                Ret = ms.ToArray();
            }
        } catch (Exception ex) {
            throw;
        }
        return Convert.ToBase64String(Ret);
    }
    #endregion
}
    public class ImageConfiguration : IEntityTypeConfiguration<MyImage> {
    public void Configure(EntityTypeBuilder<MyImage> builder) {
        builder.ToTable("Image");

        builder.HasKey(i => i.Id);

        builder.Property(i => i.Name)
            .HasMaxLength(40)
            .IsRequired(true);

        builder.Property(i => i.Country)
            .HasMaxLength(84)
            .IsRequired(true);

        builder.Property(i => i.Content)
            .IsRequired(true);
    }
}
    public class Visitor {

    #region Fields
    private string _name;
    private string _email;
    private string _telephone;
    #endregion

    #region Properties
    public int Id { get; set; }
    public string Name {
        get {
            return _name;
        }
        set {
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) {
                throw new ArgumentException("Name can't be empty.");
            }
            _name = value;
        }
    }

    public string Email {
        get {
            return _email;
        }
        set {
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) {
                throw new ArgumentException("Email can't be empty.");
            }
            Regex regex = new Regex(@"^([a-zA-Z0-9éèà]+[a-zA-Z0-9.-éèàïëöüäîôûêâù]*)@([a-zA-Z]+)[.]([a-z]+)([.][a-z]+)*$");
            Match match = regex.Match(value);
            if (!match.Success) {
                throw new ArgumentException("Email doesn't have a correct format.");
            }
            _email = value;
        }
    }

    public string Telephone {
        get {
            return _telephone;
        }
        set {
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) {
                throw new ArgumentException("Telephone number can't be empty.");
            }
            Regex regex = new Regex(@"(\+(0)?|00)(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$");
            Match match = regex.Match(value);
            if (!match.Success) {
                throw new ArgumentException("Telephone number doesn't have a correct format. " +
                    "Please make sure you use an international phone number (+44791112345) and dont forget to add the +.");
            }
            _telephone = value;
        }
    }

    public string Country { get; set; }

    public ICollection<LikedImage> Liked { get; private set; }
    public IEnumerable<MyImage> LikedImages => Liked.Select(i => i.Image);
    #endregion

    #region Constructor
    public Visitor(string name, string email, string telephone, string country = null) {
        Name = name;
        Email = email;
        Telephone = telephone;
        Country = country;
    }
    #endregion
}
public class VisitorConfiguration : IEntityTypeConfiguration<Visitor> {
    public void Configure(EntityTypeBuilder<Visitor> builder) {
        builder.ToTable("Visitors");

        builder.HasKey(v => v.Id);

        builder.Property(v => v.Name)
            .HasMaxLength(50)
            .IsRequired(true);

        builder.Property(v => v.Email)
            .HasMaxLength(70)
            .IsRequired(true);

        builder.Property(v => v.Telephone)
            .HasMaxLength(15)
            .IsRequired(true);
    }
}
   public class LikedImage {
    #region Properties
    public int ImageId { get; set; }

    public int VisitorId { get; set; }

    public Visitor Visitor { get; set; }

    public MyImage Image { get; set; }
    #endregion
}
    public class ImageVisitorConfiguration : IEntityTypeConfiguration<LikedImage> {
    public void Configure(EntityTypeBuilder<LikedImage> builder) {
        builder.HasKey(i => new { i.ImageId, i.VisitorId });

        builder.HasOne(i => i.Visitor)
            .WithMany(v => v.Liked)
            .HasForeignKey(i => i.VisitorId);

        builder.HasOne(i => i.Image)
            .WithMany()
            .HasForeignKey(i => i.ImageId);
    }
}
    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().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<ApplicationDbContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("DigitizedContext")));

        services.AddScoped<DataInitializer>();
        services.AddScoped<IImageRepository, ImageRepository>();
        services.AddScoped<IVisitorRepository, VisitorRepository>();

        services.AddOpenApiDocument(c => {
            c.DocumentName = "apidocs";
            c.Title = "DigitizedAPI";
            c.Version = "v1";
            c.Description = "The DigitizedAPI documentation description.";
            c.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT Token", new SwaggerSecurityScheme {
                Type = SwaggerSecuritySchemeType.ApiKey,
                Name = "Authorization",
                In = SwaggerSecurityApiKeyLocation.Header,
                Description = "Copy 'Bearer' + valid JWT token into field"
            }));
            c.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT Token"));
        });

        services.AddIdentity<IdentityUser, IdentityRole>(cfg => cfg.User.RequireUniqueEmail = true).AddEntityFrameworkStores<ApplicationDbContext>();
        services.Configure<IdentityOptions>(options => {

            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 3;
            options.Lockout.AllowedForNewUsers = true;

            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-._@+";
            options.User.RequireUniqueEmail = true;
        });

        services.AddAuthentication(x => {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x => {
            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                ValidateIssuer = false,
                ValidateAudience = false,
                RequireExpirationTime = true
            };
        });

        //change later to the origen of my site
        services.AddCors(options =>
    options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()
));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, DataInitializer dataInitializer) {
        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
        } else {
            // 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.UseAuthentication();

        app.UseMvc();

        app.UseSwaggerUi3();
        app.UseSwagger();

        app.UseCors("AllowAllOrigins");

        //dataInitializer.InitializeData().Wait();
        dataInitializer.InitializeData();
    }
}