簡體   English   中英

Dotnet Web API 項目自動生成控制器的 POST 方法問題

[英]Issue with POST method of Auto generated Controller for Dotnet Web API project

我正在嘗試通過為我的實體框架生成的 DB 表模型創建控制器來學習 Dotnet 5 Web API。 DB 結構非常簡單,包含 3 個表(PaymentDetail、CustomerDetail 和 ClubStateDetail)。 通過 EF 生成的 DBContext 文件具有如下所示的構造函數:

public partial class PaymentDetailDBContext : DbContext
    {
        public PaymentDetailDBContext()
        {
        }

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

        public virtual DbSet<ClubStateDetail> ClubStateDetails { get; set; }
        public virtual DbSet<CustomerDetail> CustomerDetails { get; set; }
        public virtual DbSet<PaymentDetail> PaymentDetails { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer("Server=.;Database=PaymentDetailDB;Trusted_Connection=True;");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

            modelBuilder.Entity<ClubStateDetail>(entity =>
            {
                entity.HasKey(e => e.ClubStateId);

                entity.ToTable("ClubStateDetail");

                entity.Property(e => e.ClubStateId)
                    .ValueGeneratedNever()
                    .HasColumnName("ClubStateID");

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasMaxLength(50);
            });

            modelBuilder.Entity<CustomerDetail>(entity =>
            {
                entity.HasKey(e => e.CardOwnerId);

                entity.ToTable("CustomerDetail");

                entity.Property(e => e.CardOwnerId)
                    .ValueGeneratedNever()
                    .HasColumnName("CardOwnerID");

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasMaxLength(100);

                entity.HasOne(d => d.ClubStateNavigation)
                    .WithMany(p => p.CustomerDetails)
                    .HasForeignKey(d => d.ClubState)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_CustomerDetail_ClubStateDetail");
            });

            modelBuilder.Entity<PaymentDetail>(entity =>
            {
                entity.ToTable("PaymentDetail");

                entity.Property(e => e.PaymentDetailId).HasColumnName("PaymentDetailID");

                entity.Property(e => e.CardNumber).HasMaxLength(15);

                entity.Property(e => e.CardOwnerId).HasColumnName("CardOwnerID");

                entity.Property(e => e.Cvv)
                    .HasMaxLength(6)
                    .HasColumnName("CVV");

                entity.Property(e => e.Expirationdate).HasMaxLength(6);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }

首先,由於每個客戶都必須擁有一個 ClubState,因此我創建了 ClubState 控制器,其 POST 方法如下所示:

// POST: api/ClubStateDetails
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<ClubStateDetail>> PostClubStateDetail(ClubStateDetail clubStateDetail)
        {
            _context.ClubStateDetail.Add(clubStateDetail);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetClubStateDetail", new { id = clubStateDetail.ClubStateId }, clubStateDetail);
        }

現在,我轉到 Swagger UI 來測試這個 API,它要求請求正文 JSON 數據采用以下格式(請注意,我已經為我的 clubStateId 和 name 設置了值):

{
  "clubStateId": 1,
  "name": "Gold",
  "customerDetails": [
    {
      "cardOwnerId": 0,
      "name": "string",
      "clubState": 0
    }
  ]
}

由於我目前沒有任何客戶,因此我將這些值保持不變,它們在 Swagger 提供的示例 JSON 數據中保持原樣(我意識到,這可能是一個問題,但由於我現在沒有任何客戶,我不知道該放什么)。

現在,當我嘗試執行此 POST 請求時,我收到一條錯誤消息

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'ClubStateNavigationClubStateId'.

ClubStateNavigationClubStateId不是我 ClubState 表中的一列,但是當我查看 CustomerDetail 控制器預期的 JSON 數據時,我確實看到了這一點:

{
  "cardOwnerId": 0,
  "name": "string",
  "clubState": 0,
  "clubStateNavigation": {
    "clubStateId": 0,
    "name": "string",
    "customerDetails": [
      null
    ]
  }
}

所以我的問題是,當我還沒有准備好任何客戶時,如何使用我的 API 發布數據?

Microsoft.EntityFrameworkCore.DbUpdateException:更新條目時出錯。 有關詳細信息,請參閱內部異常。 ---> Microsoft.Data.SqlClient.SqlException (0x80131904): 無效的列名“ClubStateNavigationClubStateId”。

這意味着數據庫與 EF DbContext 配置不匹配。 EF 認為數據庫中不存在名為ClubStateNavigationClubStateId的列。

您是否對數據庫中的模型進行了逆向工程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM