获取IEnumerable的值,而不必硬编码它



我正在尝试添加一个Razor页面,该页面将显示属于同一公司子组标识符下的所有商店中的employee。如果我在var employees中硬编码值.Contains("ABC"),那么我将得到该公司及其子组中的人员列表。如果我尝试使用var currentEmpSub,那么我不会得到我的列表。我不确定我需要做什么(添加另一个变量?修复我的LINQ查询?或者别的什么)。任何建议都会很有帮助!一旦我得到这个,我也将为经理视图做一个,它将只显示经理商店下的员工(而不是子组)。

设置是与EFCore 5.0的多对多关系

public class Employee
{
public int Id {get; set;}
public string Name {get; set;]
public ICollection<Tenant> Tenants {get; set;}
}
public class Tenant
{
public int Id {get; set;}
public string Name {get; set;]
public ICollection<Employee> Employees{get; set;}
}

Admin.cs

public async Task<IEnumerable<Employee>> GetAllEmployees()
{
var currentEmp = _httpContextAccessor.HttpContext?.User.GetUserId();

var currentEmpTenant = await _context.Employees
.Include(x => x.Tenants)
.Where(e => e.AspUserId == currentEmp)
.FirstAsync();
var currentEmpSub = currentEmpTenant.Tenants
.Select(x => x.SubName)
.ToString();

var employees = _context.Employees
.IgnoreQueryFilters()
.Include(t => t.Tenants)
.Where(x => x.Tenants
.Select(sub => sub.SubName)
.Contains(currentEmpSub))
.ToListAsync();
return await employees;
}

Index.cshtml

@page
@using Navrae.DataLayer.Extensions
@model Navrae.WebApp.Pages.Admin.IndexModel
@{
}
<h2>Employee List</h2>
<table class="table-hover">
<thead>
<tr>
<th>Employee Name</th>
<th>Store</th>
</tr>
</thead>
<tbody>
@foreach (var emp in @Model.Employees)
{
<tr>
<td>@emp.FullName</td>
<td>
@foreach (var comp in emp.Tenants)
{
if (emp.Tenants.Count > 1)
{
String.Join(", ", @comp.CompanyName);
}
else
{
@comp.CompanyName
}
}
</td>
</tr>
}
</tbody>
</table>

Index.cshtml.cs

public class IndexModel : PageModel
{
private readonly IAdminView _adminView;
public IndexModel(IAdminView adminView)
{
_adminView = adminView;
}
public IEnumerable<Employee> Employees { get; set; }
public async Task OnGetAsync()
{
Employees = await _adminView.GetAllEmployees();
}
}

用户@Ivan Stoev指出,通过调用。tostring()生成一个List。虽然它没有解决我的问题,但它是一个意想不到的副作用。我在currentEmpSub的末尾使用了. singleordefault(),并获得了我正在寻找的结果。

**注意你也可以使用。single () .First() .FirstOrDefault()

var currentEmpSub = currentEmpTenant.Tenants
.Select(x => x.SubName)
.SingleOrDefault();
``

相关内容

最新更新