Я начинаю новый проект в asp net core 3.1.1 , используя базу данных MYSQL. Мне удалось создать леса для моделей с помощью следующей команды
dotnet ef dbcontext scaffold "Server=localhost;User=root;Password=123456;Database=proyecto;TreatTinyAsBoolean=true;" Pomelo.EntityFrameworkCore.MySql -o Models
Но когда я пытаюсь сгенерировать любой контроллер, используя кодовый генератор pnet, он генерирует следующую ошибку: Опция «сервер данных» не поддерживается.
Attempting to figure out the EntityFramework metadata for the model and DbContext: 'Contacto'
Option 'data server' not supported. StackTrace:
at MySql.Data.MySqlClient.MySqlConnectionStringOption.GetOptionForKey(String key) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnectionStringBuilder.cs:line 435
at MySql.Data.MySqlClient.MySqlConnectionStringBuilder.set_Item(String key, Object value) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnectionStringBuilder.cs:line 345
at System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(String value)
at MySql.Data.MySqlClient.MySqlConnectionStringBuilder..ctor(String connectionString) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnectionStringBuilder.cs:line 18
at Microsoft.EntityFrameworkCore.MySqlDbContextOptionsExtensions.UseMySql(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 mySqlOptionsAction)
at Lcore.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass3_0`2.<AddDbContextPool>b__0(IServiceProvider _, DbContextOptionsBuilder ob)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass5_0`2.<AddDbContextPool>b__0(IServiceProvider sp, DbContextOptionsBuilder ob)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.CreateDbContextOptions[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__DisplayClass10_0`1.<AddCoreServices>b__0(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
Option 'data server' not supported.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__10`1.<AddCoreServices>b__10_1(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetServices[T](IServiceProvider provider)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextTypes()
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.FindContextType(String name)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
at Microsoft.EntityFrameworkCore.Design.DbContextActivator.CreateInstance(Type contextType, Assembly startupAssembly, IOperationReportHandler reportHandler)
at Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.EntityFrameworkModelProcessor.TryCreateContextUsingAppCode(Type dbContextType, Type startupType)
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0()
at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
Команда, которую я использую для генерации контроллера, выглядит следующим образом:
dotnet aspnet-codegenerator controller -name ContactosController -dc LCoreContext -outDir Controllers -actions -m Contacto -f
Это мой DbContext
using System;
using System.Configuration;
using Lcore.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
namespace Lcore.Data
{
public partial class LCoreContext : DbContext
{
public LCoreContext()
{
}
public LCoreContext(DbContextOptions<LCoreContext> options)
: base(options)
{
}
public virtual DbSet<Comprobante> Comprobante { get; set; }
public virtual DbSet<Contacto> Contacto { get; set; }
public virtual DbSet<ContactoImagen> ContactoImagen { get; set; }
public virtual DbSet<Domicilio> Domicilio { get; set; }
public virtual DbSet<EntidadFiscalContacto> EntidadFiscalContacto { get; set; }
public virtual DbSet<EntidadFiscal> EntidadFiscal { get; set; }
public virtual DbSet<Localidad> Localidad { get; set; }
public virtual DbSet<SituacionTributaria> SituacionTributaria { get; set; }
public virtual DbSet<TipoIdentificacion> TipoIdentificacion { get; set; }
public virtual DbSet<Usuarios> Usuarios { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
// optionsBuilder.UseMySql("treattinyasboolean=true", x => x.ServerVersion("10.3.14-mariadb"));
optionsBuilder.UseMySql(ConfigurationManager.ConnectionStrings["LCoreConnection"].ConnectionString + "treattinyasboolean=true; " , x => x.ServerVersion("10.3.14-mariadb"));
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Comprobante>(entity =>
{
entity.ToTable("comprobantes");
entity.HasIndex(e => e.LocalidadId)
.HasName("IDX_18EDF3E967707C89");
entity.Property(e => e.Id)
.HasColumnName("id")
.HasColumnType("int(11)");
entity.Property(e => e.Acronimo)
.IsRequired()
.HasColumnName("acronimo")
.HasColumnType("varchar(8)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_unicode_ci");
entity.Property(e => e.Activo).HasColumnName("activo");
entity.Property(e => e.Discrimina).HasColumnName("discrimina");
entity.Property(e => e.FechaCreado)
.HasColumnName("fecha_creado")
.HasColumnType("datetime");
entity.Property(e => e.FechaEditado)
.HasColumnName("fecha_editado")
.HasColumnType("datetime");
entity.Property(e => e.LocalidadId)
.HasColumnName("localidad_id")
.HasColumnType("int(11)");
entity.Property(e => e.Nombre)
.IsRequired()
.HasColumnName("nombre")
.HasColumnType("varchar(64)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_unicode_ci");
entity.Property(e => e.Nota)
.HasColumnName("nota")
.HasColumnType("varchar(124)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_unicode_ci");
entity.HasOne(d => d.Localidad)
.WithMany(p => p.Comprobante)
.HasForeignKey(d => d.LocalidadId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_18EDF3E967707C89");
});
modelBuilder.Entity<Contacto>(entity =>
{
entity.ToTable("contactos");
entity.HasIndex(e => e.ImagenId)
.HasName("UNIQ_3446F2C5763C8AA7")
.IsUnique();
entity.HasIndex(e => e.LocalidadId)
.HasName("IDX_3446F2C567707C89");
entity.HasIndex(e => e.TipoIdentificacionId)
.HasName("IDX_3446F2C565478DC6");
entity.Property(e => e.Id)
.HasColumnName("id")
.HasColumnType("int(11)");
entity.Property(e => e.Activo).HasColumnName("activo");
entity.Property(e => e.Apellidos)
.IsRequired()
.HasColumnName("apellidos")
.HasColumnType("varchar(64)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_unicode_ci");
entity.Property(e => e.FechaCreado)
.HasColumnName("fecha_creado")
.HasColumnType("datetime");
entity.Property(e => e.FechaEditado)
.HasColumnName("fecha_editado")
.HasColumnType("datetime");
entity.Property(e => e.FechaNacimiento)
.HasColumnName("fecha_nacimiento")
.HasColumnType("date");
entity.Property(e => e.Genero)
.HasColumnName("genero")
.HasColumnType("smallint(6)");
entity.Property(e => e.ImagenId)
.HasColumnName("imagen_id")
.HasColumnType("int(11)");
entity.Property(e => e.LocalidadId)
.HasColumnName("localidad_id")
.HasColumnType("int(11)");
entity.Property(e => e.Nombres)
.IsRequired()
.HasColumnName("nombres")
.HasColumnType("varchar(64)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_unicode_ci");
entity.Property(e => e.Nota)
.HasColumnName("nota")
.HasColumnType("varchar(124)")
.HasCharSet("utf8mb4")
.HasCollation("utf8mb4_unicode_ci");
entity.Property(e => e.NumeroIdentificacion)
.HasColumnName("numero_identificacion")
.HasColumnType("int(11)");
entity.Property(e => e.TipoIdentificacionId)
.HasColumnName("tipo_identificacion_id")
.HasColumnType("int(11)");
entity.HasOne(d => d.Imagen)
.WithOne(p => p.Contacto)
.HasForeignKey<Contacto>(d => d.ImagenId)
.HasConstraintName("FK_3446F2C5763C8AA7");
entity.HasOne(d => d.Localidad)
.WithMany(p => p.Contacto)
.HasForeignKey(d => d.LocalidadId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_3446F2C567707C89");
entity.HasOne(d => d.TipoIdentificacion)
.WithMany(p => p.Contacto)
.HasForeignKey(d => d.TipoIdentificacionId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_3446F2C565478DC6");
});
.
.
.
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}
Это модель
namespace Lcore.Models
{
public partial class Contacto
{
public Contacto()
{
EntidadFiscalContacto = new HashSet<EntidadFiscalContacto>();
}
public int Id { get; set; }
public int? NumeroIdentificacion { get; set; }
public string Nombres { get; set; }
public string Apellidos { get; set; }
public DateTime? FechaNacimiento { get; set; }
public short? Genero { get; set; }
public int TipoIdentificacionId { get; set; }
public int LocalidadId { get; set; }
public int? ImagenId { get; set; }
public DateTime FechaCreado { get; set; }
public DateTime FechaEditado { get; set; }
public string Nota { get; set; }
public bool Activo { get; set; }
public virtual ContactoImagen Imagen { get; set; }
public virtual Localidad Localidad { get; set; }
public virtual TipoIdentificacion TipoIdentificacion { get; set; }
public virtual ICollection<EntidadFiscalContacto> EntidadFiscalContacto { get; set; }
}
}
И это моя конфигурация служб в файле startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// other service configurations go here
// replace "YourDbContext" with the class name of your DbContext
services.AddDbContextPool<LCoreContext>(options => options
// replace with your connection string
.UseMySql(Configuration.GetConnectionString("LCoreConnection"), mySqlOptions => mySqlOptions
// replace with your Server Version and Type
.ServerVersion(new Version(10, 3, 14), ServerType.MySql)
));
}
Ошибка подключения к базе данных не может быть так как я мог генерировать модели. А с другой стороны, я пытался создать контроллер без соответствующей модели, и у меня не было проблем. Я использовал эту команду.
dotnet aspnet-codegenerator controller -name ContactosController -dc LCoreContext -outDir Controllers -actions
Любая помощь или намек, который вы можете мне дать, я буду очень признателен.