0
I’m starting to learn Asp.Net Core, and I’m trying a problem regarding a user registration, because when I try to create it returns an internal error with the message "Cannot create a Dbset for 'Usuario' because this type is not included in the model for the context"
My code is like this,
Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<RotaPontoServico>();
services.AddScoped<RotaServico>();
services.AddEntityFrameworkNpgsql().AddDbContext<Context>(opt =>
opt.UseNpgsql(Configuration.GetConnectionString("MyWebApiConnection")));
services.AddDefaultIdentity<Usuario>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<Context>()
.AddDefaultTokenProviders();
services.AddVersionedApiExplorer(opt =>
{
opt.GroupNameFormat = "'V'VVV";
opt.SubstituteApiVersionInUrl = true;
})
.AddApiVersioning(opt => {
opt.DefaultApiVersion = new ApiVersion(1, 0);
opt.AssumeDefaultVersionWhenUnspecified = true;
opt.ReportApiVersions = true;
});
var apiProviderderDescription = services.BuildServiceProvider()
.GetService<IApiVersionDescriptionProvider>();
services.AddSwaggerGen(x => {
foreach (var description in apiProviderderDescription.ApiVersionDescriptions)
{
x.SwaggerDoc(
description.GroupName,
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "AppLudis",
Version = description.ApiVersion.ToString()
}
);
}
x.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header usando o esquema bearer",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
}
);
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{new OpenApiSecurityScheme{Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}}, new List<string>()}
});
var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
x.IncludeXmlComments(xmlCommentsFullPath);
});
services.AddControllers();
services.AddAuthorization(options =>
{
options.AddPolicy(name: "CargaViewer", configurePolicy: builder => builder.RequireClaim("carga.view", allowedValues: "true"));
//options.AddPolicy("embarcador", policy => policy.RequireClaim("Store", "embarcador"));
});
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(X =>
{
X.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
X.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(X =>
{
X.RequireHttpsMetadata = false;
X.SaveToken = true;
X.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = appSettings.ValidoEm,
ValidIssuer = appSettings.Emissor
};
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env,
IApiVersionDescriptionProvider apiProviderderDescription)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSwagger();
app.UseSwaggerUI(opt =>
{
foreach (var description in apiProviderderDescription.ApiVersionDescriptions)
{
opt.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
}
opt.RoutePrefix = "";
});
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Context
public class Context : IdentityDbContext
{
public Context(DbContextOptions<Context> options) :
base(options)
{ }
// public DbSet<Usuario> Usuarios { get; set; }
public DbSet<Esportista> Esportistas { get; set; }
public DbSet<Comerciante> Comerciantes { get; set; }
public DbSet<Rota> RotaDb { get; set; }
public DbSet<RotaPonto> RotaPontoDb { get; set; }
public DbSet<IdentityUser> Usuario { get; set; }
}
Registeruserviewmodels
public class RegisterUserViewModels
{
[Required(ErrorMessage = "O campo {0} é obrigatório")]
[EmailAddress(ErrorMessage = "O campo {0} está em formato inválido")]
public string Email { get; set; }
[Required(ErrorMessage = "O campo {0} é obrigatório")]
[StringLength(100, ErrorMessage = "O campo {0} precisa ter entre {2} e {1} caracteres", MinimumLength = 6)]
public string Password { get; set; }
[Compare("Password", ErrorMessage = "As senhas não conferem.")]
public string ConfirmPassword { get; set; }
}
public class LoginUserViewModel
{
[Required(ErrorMessage = "O campo {0} é obrigatório")]
[EmailAddress(ErrorMessage = "O campo {0} está em formato inválido")]
public string Email { get; set; }
[Required(ErrorMessage = "O campo {0} é obrigatório")]
[StringLength(100, ErrorMessage = "O campo {0} precisa ter entre {2} e {1} caracteres", MinimumLength = 6)]
public string Password { get; set; }
}
Controller
private readonly SignInManager<Usuario> _signInManager;
private readonly UserManager<Usuario> _userManager;
private readonly AppSettings _appSettings;
public UsuarioController(SignInManager<Usuario> signInManager,
UserManager<Usuario> userManager,
IOptions<AppSettings> appSettings)
{
_signInManager = signInManager;
_userManager = userManager;
_appSettings = appSettings.Value;
}
[HttpPost("nova-conta")]
public async Task<ActionResult> Registrar(RegisterUserViewModels registerUser)
{
if (!ModelState.IsValid) return BadRequest(ModelState.Values.SelectMany(e => e.Errors));
var newUseId = Guid.NewGuid();
var user = new Usuario
{
Id = newUseId.ToString(),
UserName = registerUser.Email,
Email = registerUser.Email,
EmailConfirmed = true
/* Telefone = registerUser.Telefone,
Endereco = registerUser.Endereco,
CEP = registerUser.CEP,
Cidade = registerUser.Cidade,
Bairro = registerUser.Bairro,
Nome = registerUser.Nome,
Complemento = registerUser.Complemento,
UF = registerUser.UF,
IdEsportista = registerUser.IdEsportista,
IdComerciante = registerUser.IdComerciante*/
};
var result = await _userManager.CreateAsync(user, registerUser.Password);
if (!result.Succeeded) return BadRequest(result.Errors);
await _signInManager.SignInAsync(user, false);
await _userManager.AddClaimAsync(user, new Claim(type: "carga.view", value: "true"));
return Ok(await GerarJwt(registerUser.Email));
}
the error is happening on the line "var result = await _userManager.Createasync(user, registerUser.Password);"
You’ve tried the decontamination
// public DbSet<Usuario> Usuarios { get; set; }
?– tvdias
This line is documented because in the examples I saw did not use, so I commented. But I tried too and the error has changed now gives "column a.Discriminator does not exist" I’m trying to find this a.Disriminator
– Iury Pereira