如何找到没有孩子的父母记录?

时间:2019-11-21 15:41:15

标签: c# entity-framework

我有以下SQL查询

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

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

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

如何在我的代码上放置COUNT条件?

2 个答案:

答案 0 :(得分:1)

最短答案:

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]))

答案 1 :(得分:0)

尝试一下:

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