【问题标题】:How to get two different username's from joining two tables in EF Core?如何通过加入 EF Core 中的两个表来获得两个不同的用户名?
【发布时间】:2020-11-17 20:27:06
【问题描述】:

我需要在表中显示数据,其中createdByupdatedBy 属性显示从Users 表中获取的两个不同用户名。

这是我目前得到的:

IQueryable<Services> result;

result = (from u in _appContext.Users
          join s in _appContext.Services
                 on u.Id equals s.UpdatedBy
          select new Services
                     {
                         Id = s.Id,
                         CreatedBy = u.UserName, // this should display: admin
                         CreatedDate = s.CreatedDate,
                         UpdatedBy = u.UserName, // this should display: user
                         IsActive = s.IsActive,
                         UpdatedDate = s.UpdatedDate  
                     }).OrderByDescending(s => s.Id);

这样我在createdByupdatedBy 上都显示了相同的(不正确的)用户名。在数据库中,这两个属性存储了正确的userId

我该如何解决这个问题?抱歉,如果我的问题不清楚!

【问题讨论】:

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


    【解决方案1】:

    您可以反转您的 from/join 然后添加第二个连接:

    var result = from s in _appContext.Services
      join cu in _appContext.Users on cu.Id equals s.CreatedBy
      join uu in _appContext.Users on uu.Id equals s.UpdatedBy
      
    select new Services 
    {
      Id = s.Id,
      CreatedBy = cu.UserName,
      CreatedDate = s.CreatedDate,
      UpdatedBy = uu.UserName,
      IsActive = s.IsActive,
      UpdatedDate = s.UpdatedDate  
    });
    

    注意:我没有使用真实数据对此进行测试。

    【讨论】:

    • 谢谢!我尝试了同样的东西哈哈,但很快就放弃了。这非常有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多