C# LINQ选择列表中的所有孤儿

C# LINQ选择列表中的所有孤儿,c#,linq,entity-framework-core,C#,Linq,Entity Framework Core,我正在使用C语言中的以下模型 public class Bill { public Guid Id { get; set; } public Document Document { get; set; } } public class Document { public Guid Id { get; set; } public List<Payment> Payments { get; set; } } public class Payment

我正在使用C语言中的以下模型

public class Bill
{
    public Guid Id { get; set; }

    public Document Document { get; set; }
}

public class Document
{
    public Guid Id { get; set; }

    public List<Payment> Payments { get; set; }
}

public class Payment
{
    public Guid Id { get; set; }
}
但若该文档只包含一笔付款,而不是一个完整的列表,那个么这种方法是有效的


您知道如何调整查询以检索所有孤立付款吗?

嗯,EFC至少比EF6更好的一点是,它允许您使用方法访问LINQ中的查询

在此特定情况下,阴影FK属性。所以你可以用这样的东西

.Where(p => EF.Property<Guid?>(p, "DocumentId") == null)

缺点是您需要知道确切的shadow属性名称和类型,而编译器不会为此提供帮助。

如果您有导航属性返回到父文档。那么它就很容易了,因为db.Payments.Wherep=>p.Document==null@TheGeneral-当我看到这个的时候,我也在想同样的事情。这就是为什么许多ORM会创建列表,即使它不存在于底层数据中。允许类似于此代码的迭代,但也保持支付对象的完整性..Wherep=>!db.Documents.Anyd=>d.Payments.Anyp2=>p.Id==p2.Id将是一种非常低效的方法。请参阅副本。更好的做法是继续创建一个数据结构,将支付对象映射回父文档对象(如果不在数据库中),然后根据需要至少内置内存以执行此类过滤。感谢您的参与,不幸的是,我无法进行任何修改,因为我正在将API反向工程到DB中,并且我需要将其与源代码保持1:1。我想这可能会解决我的问题@PeterDuniho我在问你之前试过你的解决方案,但我觉得它有严重的问题:D@andreucci为什么不将foreignKey DocumentId添加到付款表中?
 // All the payments whose id is not contained in any of all the           
//Documents.Payments
   List<Payment> paymentList = db.Payments
        .Where(p => db.Documents.SelectMany(d => d.Payments)
        .All(p2 => p2.Id != p.Id));
 // All the payments whose id is not contained in any of all the           
//Documents.Payments
   List<Payment> paymentList = db.Payments
        .Where(p => db.Documents.SelectMany(d => d.Payments)
        .All(p2 => p2.Id != p.Id));