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

Entity Framework 6如何通过子查询根据用户ID获取用户名?

问题解决及代码修正

原代码的核心问题

  1. EF6语法错误:EF6不支持ThenInclude方法,该方法是EF Core引入的,EF6需用嵌套Include加载关联对象
  2. 空引用触发点:当x.Constituent对应的用户不存在时,FirstOrDefault()返回null,调用.ToString()直接抛出NullReferenceException;同时获取companiesId和Assigned字段时未处理关联对象为空的情况
  3. 冗余操作:Name本身是字符串类型,无需额外调用.ToString()

修正后的代码

// 安全获取企业ID,避免用户不存在或关联企业为空的情况
int companiesId = context.Users
    .Where(x => x.Id == UserId && x.Companies != null)
    .Select(x => x.Companies.Id)
    .FirstOrDefault();

tasksList1 = context.Tasks
    .Where(x => x.User != null && x.User.Companies != null && x.User.Companies.Id == companiesId)
    .Include(x => x.User.Companies) // EF6用嵌套Include替代ThenInclude
    .Include(x => x.Documents)
    .Select(x => new ListTaskViewModel
    {
        Assigned = x.User?.Name ?? "未知用户", // 处理用户为空的边界情况
        // 子查询获取用户名,用null合并运算符避免空引用
        Constituent = context.Users
            .Where(c => c.Id == x.Constituent)
            .Select(v => v.Name)
            .FirstOrDefault() ?? "未知用户",
        Title = x.Title,
        Description = x.Description,
        Priority = x.Priority,
        Urgency = x.Urgency,
        CompletionTime = x.CompletionTime,
        DocumentViewModels = x.Documents.ToList()
    })
    .ToList();

优化建议(更高效的实现方式)

如果你的Task实体中已经定义了与Constituent用户的导航属性(比如public User ConstituentUser { get; set; }),可以直接使用导航属性替代子查询,EF会自动处理关联查询,代码更简洁高效:

// 假设Task实体有ConstituentUser导航属性
Constituent = x.ConstituentUser?.Name ?? "未知用户",

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:24:22