You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core 7查询仅返回主键列,未选择其他列的问题排查

问题:EF Core 7查询仅返回主键列,未获取所有字段

我有一个简单标准的数据库表,尝试通过EF Core 7获取数据。

我的实体模型类如下:

[Table("APComment")]
public class ApplicationCommentModel
{
    [Key]
    [Column("recid")]
    [Required]
    public int Id { get; set; }

    [Column("InvoiceNo")]
    [Required]
    [MaxLength(8)]
    public string InvoiceNumber;

    [Column("InvoiceLineNo")]
    [Required]
    public int InvoiceLineNumber;

    [MaxLength(988)]
    public string? CommentText;
}

我使用以下代码加载数据:

public async Task<List<ApplicationCommentModel>> GetAllAsync()
{
    using (var context = _contextCreator())
    {
        var comments = context.ApplicationComments.ToList();
        return comments;
    }
}

但查看数据库查询输出时,发现仅执行了如下SQL:

Microsoft.EntityFrameworkCore.Database.Command: Information: Executed DbCommand (37ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [a].[recid]
FROM [APComment] AS [a]
The program '[27792] CompanyAddressMaintenance.exe' has exited with code 4294967295 (0xffffffff).

我期望查询recid、InvoiceNo、InvoiceLineNo、CommentText所有列,但实际并未实现。使用的是EF Core 7.0.10库,请问哪里出错了?


解决方案

问题出在实体模型类中:InvoiceNumber、InvoiceLineNumber、CommentText是普通字段,不是带访问器的属性。EF Core默认仅识别带有get/set访问器的属性进行数据库映射,不会处理无访问器的字段,因此只会查询被正确映射的主键属性Id(对应数据库recid列)。

只需把这些字段修改为自动属性,添加get; set;访问器即可:

[Table("APComment")]
public class ApplicationCommentModel
{
    [Key]
    [Column("recid")]
    [Required]
    public int Id { get; set; }

    [Column("InvoiceNo")]
    [Required]
    [MaxLength(8)]
    public string InvoiceNumber { get; set; }

    [Column("InvoiceLineNo")]
    [Required]
    public int InvoiceLineNumber { get; set; }

    [MaxLength(988)]
    public string? CommentText { get; set; }
}

修改后,EF Core会正确映射所有属性到对应数据库列,执行查询时就会获取所有你需要的字段。


内容的提问来源于stack exchange,提问作者PHenry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:12:21