I'm trying to insert a record of a many-to-many relationship to a ASP.NET Core 2.1 API, I'm doing it with postman, but I get this error:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.

System.Data.SqlClient.SqlException: Invalid column name 'AfiliadosId'.

at System.Data.SqlClient.SqlCommand.<>c.b__122_0(Task1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask
2.InnerInvoke()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown --

at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown --

at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary2 parameterValues, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple
2 parameters, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func4 operation, Func4 verifySucceeded, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList1 entriesToSave, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at WebAPI.Controllers.AfiliadosCreditosController.PostAfiliadosCreditos(AfiliadosCreditos afiliadosCreditos) in D:\pruebaEmergia\WebAPI\WebAPI\Controllers\AfiliadosCreditosController.cs:line 99 at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at System.Threading.Tasks.ValueTask1.get_Result() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 9999.2762ms 500 text/html; charset=utf-8

My code:

Entity afiliados

//------------------------------------------------------------
using System;
using System.Collections.Generic;

namespace WebAPI.Models.data
{
    public partial class Afiliados
    {
        public byte Id { get; set; }
        public string Nombre { get; set; }
        public string Apellido { get; set; }
        public byte Cedula { get; set; }
        public string Estado { get; set; }
        public string AdminId { get; set; }
        public ApplicationUser Admin { get; set; }
        public List<AfiliadosCreditos> AfiliadosCreditos { get; set; }
    }
}

Entity creditos

using System;
using System.Collections.Generic;

namespace WebAPI.Models.data
{
    public partial class Creditos
    {
        public byte Id { get; set; }
        public string Credito { get; set; }
        public List<AfiliadosCreditos> AfiliadosCreditos { get; set; }
    }
}

Entity AfiliadosCreditos

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI.Models.data
{
    public class AfiliadosCreditos
    {
        public float Taza { set; get; }
        [Key]
        public byte CreditoId { get; set; }
        public Creditos Credito { get; set; }
        [Key]
        public byte AfiliadosId { get; set; }
        public Afiliados Afiliados { get; set; }
    }
}

DbContext:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.Models.data;

namespace WebAPI.Models
{
    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<AfiliadosCreditos>().HasKey(x 
                            => new { x.CreditoId, x.AfiliadosId });
            modelBuilder.Entity<AfiliadosCreditos>()
                         .HasOne(x => x.Afiliados)
                         .WithMany(x => x.AfiliadosCreditos)
                         .HasForeignKey(x => x.AfiliadosId);
            modelBuilder.Entity<AfiliadosCreditos>()
                           .HasOne(x => x.Credito)
                           .WithMany(x => x.AfiliadosCreditos)
                           .HasForeignKey(x => x.CreditoId);

            base.OnModelCreating(modelBuilder);
        }

        public DbSet<ApplicationUser> ApplicationUsers { get; set; }
        public DbSet<Afiliados> Afiliados { get; set; }
        public DbSet<Creditos> Creditos { get; set; }
        public DbSet<AfiliadosCreditos> AfiliadosCreditos { get; set; }
    }
}

Controller

public async Task<IActionResult> PostAfiliadosCreditos([FromBody] AfiliadosCreditos afiliadosCreditos)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _context.AfiliadosCreditos.Add(afiliadosCreditos);

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (AfiliadosCreditosExists(afiliadosCreditos.CreditoId))
        {
            return new StatusCodeResult(StatusCodes.Status409Conflict);
        }
        else
        {
            throw;
        }
    }

    return CreatedAtAction("GetAfiliadosCreditos", new { id = afiliadosCreditos.CreditoId }, afiliadosCreditos);
}

I want to insert one register

0 Answers