ef核心只返回所包含的实体

时间:2020-06-11 12:22:47

标签: c# entity-framework async-await entity-framework-core asp.net-core-webapi

在ef核心中,我有一个合同实体,其中有一个PaymentRequirement实体。我只想带给定合同ID的付款要求实体。

public async Task<PaymentRequirement> GetPaymentRequirementByContractAsync(long Id) =>
            await context.Contracts.Include(p => p.PaymentRequirement).FirstOrDefaultAsync(p => p.Id == Id)?.PaymentRequirement

严重性代码描述项目文件行抑制状态 错误CS1061“任务”不包含以下内容的定义: “ PaymentRequirement”,没有可访问的扩展方法 “ PaymentRequirement”接受类型的第一个参数 可以找到“任务”(您是否缺少using指令或 大会 参考?)Minerals C:\ Users \ c-bdelling \ source \ repos \ Minerals \ Minerals \ Repositories \ PaymentRequirementRepository.cs 15有效

这是合同

 public class Contract : AuditedEntity
    {
        public long Id { get; set; }       
        public long? PaymentRequirementId { get; set; }
        public PaymentRequirement PaymentRequirement { get; set; }

    }

这是付款要求

 public class PaymentRequirement
    {
        public long Id { get; set; }
        public decimal? FloorPrice { get; set; }
    }

1 个答案:

答案 0 :(得分:2)

正在等待整个表达式的结果,并且无法等待PaymentRequirement

context.Contracts
    .Include(p => p.PaymentRequirement)
    .FirstOrDefaultAsync(p => p.Id == Id)?
    .PaymentRequirement

您确实需要等待FirstOrDefaultAsync的结果,并且可以通过引入括号来实现:

(await context.Contracts
    .Include(p => p.PaymentRequirement)
    .FirstOrDefaultAsync(p => p.Id == Id))?
    .PaymentRequirement

话虽如此,假设您的上下文中PaymentRequirementsDbSet,应该有一种更清洁的方法:

await context.PaymentRequirements
    .FirstOrDefaultAsync(p => context.Contracts
        .Any(c => c.Id == Id && c.PaymentRequirement == p));

这样,将从数据库中仅返回PaymentRequirement而不是Contract