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

EF Core MySQL下LINQ查询无结果但原生SQL正常?求排查

EF Core + MySQL:原生SQL返回结果但LINQ查询为空的问题

在C# EF Core + MySQL环境中,使用原生SQL查询能返回预期的准确结果,但逻辑一致的LINQ查询始终返回空结果——即使移除Include语句也无效。已按照EF Core官方文档配置表关系,将CustomerId设为可空类型(预期EF会自动生成LEFT JOIN),且通过.EnsureCreated()重新生成数据库,核对过关联字段(LibraryCustomer的Id),问题仍未解决。

原生SQL代码(可正常返回结果)

var IdSubProduct = new MySqlConnector.MySqlParameter("IdSubProduct", this.parameter.Id.ToString());

FormattableString cmd = $@"SELECT spr.*, c.Name CustomerName FROM ProductSubProductRate spr 
LEFT JOIN LibraryCustomer c ON (c.Id = spr.CustomerId)
WHERE (spr.IdSubProduct = {IdSubProduct})";
this.contextSQL.ProductSubProductRate.FromSql(cmd).ToList();

LINQ查询代码(返回空结果)

this.contextSQL.ProductSubProductRate
.Include("Customers")
.Where(pr => pr.IdSubProduct == this.parameter.Id.ToString())
.Select(pr => new
{
    pr.Id,
    pr.EffectiveDate,
    pr.Rate,
    pr.Additional,
    pr.Creator,
    pr.Modifier,
    CustomerName = pr.Customers.Name
})
.OrderByDescending(pr => pr.EffectiveDate).ToList();

实体模型与上下文配置

DbContext的OnModelCreating配置

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<modelLibraryCustomer>()
        .HasMany(e => e.SubProductRates)
        .WithOne(e => e.Customers)
        .HasForeignKey(e => e.CustomerId)
        .HasPrincipalKey(e => e.Id);
}

modelDataProductSubProductRate实体

[Index(nameof(IdSubProduct), nameof(EffectiveDate), IsUnique = true)]
internal class modelDataProductSubProductRate
{
    [Key]
    public string Id { get; set; }
    public string IdSubProduct { get; set; }
    public DateOnly EffectiveDate { get; set; }
    public decimal Rate { get; set; }
    public string Additional { get; set; }

#nullable enable
    //[ForeignKey("IdCustomer")]
    public string? CustomerId { get; set; }
#nullable disable
    public modelLibraryCustomer Customers { get; set; }

    public virtual string? CustomerName { get; set; }
}

modelLibraryCustomer实体

[Index(nameof(Name), IsUnique = true)]
internal class modelLibraryCustomer
{
    [Key]
    public string Id { get; set; }
    public string Name { get; set; }
    public string CompanyName { get; set; }
    public string Telephone { get; set; }
    public string Additional { get; set; }
    public bool Active { get; set; }

    public ICollection<modelDataProductSubProductRate> SubProductRates { get; }
}

问题核心

为何两段查询逻辑一致但结果不同?LINQ查询无返回的原因是什么?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 06:24:52