You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# EF Core如何获取关联表首条数据,为空时返回默认7天通知周期

问题原因

你遇到的报错是因为EF Core的SQL翻译器暂不支持C#的空条件运算符?.,无法将该语法糖转译为对应的SQL逻辑,所以会抛出运算不支持的异常。你可以用以下两种EF Core原生支持的写法实现需求,生成的SQL本质为LEFT JOIN + COALESCE,性能和存储过程完全一致。


方案1:使用DefaultIfEmpty指定默认值(推荐)

对筛选后的通知周期字段做投影,直接通过DefaultIfEmpty设置默认值7,无需空值判断即可实现需求:

var birthday = _birthdayRepository.GetAll()
    .Where(x => x.BirthdayId == birthdayId)
    .Select(x => new BirthdayDto
    {
        BirthdayId = x.BirthdayId,
        Forename = x.Forename,
        Surname = x.Surname,
        DateOfBirth = x.DateOfBirth,
        NotificationPeriod = x.BirthdayNotificationPeriods
            .Where(bn => bn.UserId == user.UserId)
            .Select(bn => bn.NotificationPeriod)
            .DefaultIfEmpty(7)
            .First()
    }).FirstOrDefault();

方案2:显式条件判断兼容低版本EF Core

如果使用的是EF Core 2.0及以下版本,可以用Any判断是否存在自定义配置,再对应取值:

var birthday = _birthdayRepository.GetAll()
    .Where(x => x.BirthdayId == birthdayId)
    .Select(x => new BirthdayDto
    {
        BirthdayId = x.BirthdayId,
        Forename = x.Forename,
        Surname = x.Surname,
        DateOfBirth = x.DateOfBirth,
        NotificationPeriod = x.BirthdayNotificationPeriods.Any(bn => bn.UserId == user.UserId) 
            ? x.BirthdayNotificationPeriods.First(bn => bn.UserId == user.UserId).NotificationPeriod 
            : 7
    }).FirstOrDefault();

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:27:05