如何使用实体框架将数据过多插入表?

时间:2019-05-09 22:12:44

标签: c# asp.net-core entity-framework-core

我正在尝试插入与ASP.NET Core 2.1 API的多对多关系的记录,我正在用邮递员来做,但是出现此错误:

  

Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。有关详细信息,请参见内部异常。

     

System.Data.SqlClient.SqlException:无效的列名'AfiliadosId'。

     

在System.Data.SqlClient.SqlCommand。<> c.b__122_0(任务1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask
2.InnerInvoke()
  在System.Threading.ExecutionContext.RunInternal(ExecutionContext执行上下文,ContextCallback回调,对象状态)处
  ---从之前引发异常的位置开始的堆栈跟踪-

     

在System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task&currentTaskSlot)
  ---从先前引发异常的位置开始的堆栈跟踪-

     Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteAsync中的

(IRelationalConnection连接,DbCommandMethod executeMethod,IReadOnlyDictionary 2 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个参数,CancellationToken cancelToken)      在Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync [TState,TResult](TState状态,Func 4 operation, Func 4验证成功,CancellationToken cancelToken)处      在Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IReadOnlyList 1 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.ValueTask 1.get_Result()      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext上下文)      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和isCompleted)处      在Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext上下文)      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(状态和下一个,范围和范围,对象和状态,布尔值和已完成)      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()      在Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()      在Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)      在Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext上下文)      在Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)   Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在9999.2762ms中完成500 text / html; charset = utf-8

我的代码:

实体成员

//------------------------------------------------------------
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; }
    }
}

实体信用额

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; }
    }
}

实体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; }
    }
}

控制器

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);
}

我要插入一个寄存器

0 个答案:

没有答案