首页 > 解决方案 > .NET Core Web api 中抛出无效的列名异常

问题描述

我的数据库中有两个类,它们被定义为类,输入实体,然后从 API 调用

下面是调用的完整方法。第一次调用正常,第二次抛出异常

 public async Task<ActionResult<List<QuizForms>>> GetQuiz([FromQuery]string id)
    {
        var form = await _context.QuizForms.Where(t=>t.QuizId == id).ToListAsync();

        if (form == null)
        {
            return NotFound();
        }

        var elem = new List<Element>();
        foreach(var e in form)
        {
            var data = await _context.Element.Where(t => t.ElementId == e.ElementId).ToListAsync();
            elem.AddRange(data);
            e.Element.AddRange(elem);
        }

        return form;
    }

命中var数据行时,抛出异常

Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'QuizFormsFormId'.

看起来类名和列名被连接起来并用作查询参数。

这两个类看起来像这样

public class QuizForms
{
    [Key]
    public int FormId { get; set; }
    public string QuizId { get; set; } = "";
    #nullable enable
    public string? Title { get; set; }
    public int? ElementId { get; set; }
    public List<Element>? Element { get; set; }

    public int? PreviousId { get; set; }
    public int? NextId { get; set; }
    #nullable disable
}

public class Element
{
    [Key]
    public int Id { get; set; }
    public int ElementId { get; set; }
    #nullable enable
    public int? MathsId { get; set; }
    public int? QuestionId { get; set; }
    public int? InformationId { get; set; }
    public int? AnswerId { get; set; }
    #nullable disable
    public string QuizId { get; set; } = "";
}

是因为我没有使用Id主键还是我需要做其他事情所以类和属性不会像这样连接?

标签: sql-serverasp.net-core

解决方案


推荐阅读