c# - 没有 child 的情况下如何查找家长记录?

标签 c# entity-framework

我有以下 SQL 查询

SELECT T0.*
FROM Accounting T0 
WHERE (SELECT COUNT(ParentAccountId) FROM Accounting WHERE ParentAccountId = T0.AccountId) = 0

它给了我没有 child 的帐户。我正在尝试使用 Lambda 表达式在我的代码中获得相同的结果。

List<Accounting> Items = await _context.Accounting.Where(q => q.ParentAccountId == q.AccountId).ToListAsync();

如何在代码中放置 COUNT 条件?

最佳答案

最短答案:

List<MyParent> noKidParents = myDbContext.MyParents.Where(par => !par.MyChildren.Any());

简短回答:

////using System;
////    using System.Collections.Generic;
////    using System.Linq;
////    using System.Threading;
////    using System.Threading.Tasks;

////    using Microsoft.EntityFrameworkCore;

    public async Task<IEnumerable<MyParentEntity>> GetNoChildrenRows(CancellationToken token)
    {
        List<MyParentEntity> returnItems = await this.entityDbContext.MyParents.Where(ent => !ent.MyChildren.Any()).ToListAsync(token);

        return returnItems;
    }

详细解释答案:

您不应该更喜欢“计数”答案。

您应该更喜欢“.Any()”(或在本例中为 !.Any())答案。

考虑到 POCO

public partial class MyChildEntity
{
    public Guid MyChildKey { get; set; } /* PK */

    public Guid MyParentUUID { get; set; } /* FK to the "parent" */

    public MyParentEntity ParentMyParent { get; set; }
}

public partial class MyParentEntity
{

    public MyParentEntity()
    {
        this.MyChilds = new List<MyChildEntity>();
    }

    public Guid MyParentKey { get; set; } /* PK */

    public ICollection<MyChildEntity> MyChilds { get; set; }
}

和这样的映射(我的映射被编码为 EF Core,但最终答案(下面的 .Where EF 查询)应该工作相同,即使您没有使用 EF Core,而是使用 DotNet Framework EF..只要一切都正确“映射”)

////    using Microsoft.EntityFrameworkCore;
////    using Microsoft.EntityFrameworkCore.Metadata.Builders;

   public class MyChildMap : IEntityTypeConfiguration<MyChildEntity>
    {
        public const string SchemaName = "dbo";
        public const string TableName = "MyChild";

        public void Configure(EntityTypeBuilder<MyChildEntity> builder)
        {
            builder.ToTable(TableName, SchemaName );

            builder.HasKey(k => k.MyChildKey);
            builder.Property(cnpk => cnpk.MyChildKey).HasColumnName("MyChildUUID");
            builder.Property(req => req.MyChildKey).IsRequired();

            builder.Property(cn => cn.MyParentUUID).HasColumnName("MyParentUUID");
            builder.Property(req => req.MyParentUUID).IsRequired();



            builder.HasIndex(ind => new { ind.MyParentUUID, ind.MyChildName }).IsUnique(true);

            builder.HasOne<MyParentEntity>(e => e.ParentMyParent)
            .WithMany(d => d.MyChilds)
            .HasForeignKey(e => e.MyParentUUID).HasConstraintName("MyParentUUIDFK");
        }
    }

public class MyParentMap : IEntityTypeConfiguration<MyParentEntity>
{
    public const string SchemaName = "dbo";
    public const string TableName = "MyParent";

    public void Configure(EntityTypeBuilder<MyParentEntity> builder)
    {
        builder.ToTable(TableName, SchemaName);

        builder.HasKey(k => k.MyParentKey);
        builder.Property(cnpk => cnpk.MyParentKey).HasColumnName("MyParentUUID");

        builder.Property(req => req.MyParentKey).IsRequired();


    }
}

和这样的上下文:

////using Microsoft.EntityFrameworkCore;
public class MyEntitiesDbContext : DbContext
{
    public MyEntitiesDbContext (DbContextOptions<MyEntitiesDbContext > options)
        : base(options)
    {
    }


    public DbSet<MyParentEntity> MyParents { get; set; }

    public DbSet<MyChildEntity> MyChilds { get; set; }
}

您的 EF 代码可能如下所示:

////using System;
////    using System.Collections.Generic;
////    using System.Linq;
////    using System.Threading;
////    using System.Threading.Tasks;

////    using Microsoft.EntityFrameworkCore;

    public async Task<IEnumerable<MyParentEntity>> GetNoChildrenRows(CancellationToken token)
    {
        List<MyParentEntity> returnItems = await this.entityDbContext.MyParents.Where(ent => !ent.MyChildren.Any()).ToListAsync(token);

        return returnItems;
    }

注意,在 Sql Server 中,上面的 EF“where”查询...确实(正确地)等同于“NOT EXISTS”查询:

SELECT [m].[MyParentUUID]
FROM [dbo].[MyParent] AS [m]
WHERE NOT (EXISTS (
    SELECT 1
    FROM [dbo].[MyChild] AS [m0]
    WHERE [m].[MyParentUUID] = [m0].[MyParentUUID]))

关于c# - 没有 child 的情况下如何查找家长记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58978614/

相关文章:

c# - 使用 ProtoBuff.Net 通过 Socket 接收多种类型的对象

c# - EntityFramework.Extended Future 错误(JIT 编译器内部限制)

c# - Restier - Entity Framework - LOADMEMORYQUERY

c# - Entity Framework : Get children

c# - 将一行 VB.Net 代码转换为 C#

c# - TSQL - 选择插入的行

c# - 在 C# 中使用 Bouncy CaSTLe 验证 ECDSA 签名

c# - 限制 CrmSvcUtil 以仅创建我的解决方案所需的代码

entity-framework - SqlException : An expression of non-boolean type specified in a context where a condition is expected, 附近 ')'

c# - 删除实体时,Breeze SaveChanges 总是抛出 DbUpdateConcurrencyException