【问题标题】:ef core return just the included entityef core 只返回包含的实体
【发布时间】:2020-10-01 02:13:34
【问题描述】:

在 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 Active

这是合同

 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; }
    }

【问题讨论】:

  • 你为什么用?
  • 如果合同不存在,比如 id 为 0

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


【解决方案1】:

整个表达式的结果正在等待中,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

话虽如此,应该有一种更简洁的方法,假设PaymentRequirements 在您的上下文中是DbSet

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

这样,只会从数据库返回PaymentRequirement 而不是Contract

【讨论】:

    猜你喜欢
    • 2020-11-29
    • 2021-03-31
    • 1970-01-01
    • 2015-09-06
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多