【发布时间】:2018-07-09 14:40:35
【问题描述】:
我查看了所有内容,发现了许多解决方案,但都没有给出我想要的具体结果。我一定遗漏了一些明显的东西!
我正在尝试获取用户当前角色的列表(存储在 mysql db 中)并列出与用户列表在同一个表中的列表,以下是我可以设法开始工作的所有内容,所有列表所有用户所在的角色,而不是特定于每个用户。 User 到 UserRoles 是多对多关系,因此生成了 UseRoles_has_Users 表
我为管理索引页面创建了一个单独的模型
型号
namespace ComputerAidedDispatch.Models
{
public class AdminIndex : UserMetaData
{
public IEnumerable<User> AdminUsers { get; set; }
public IEnumerable<UserRoles_has_Users> AdminUserRoles { get; set; }
}
}
控制器
public ActionResult Index(string searchString)
{
var users = from u in db.Users
select u;
var userRoles = from r in db.UserRoles_has_Users
select r;
var adminIndex = new AdminIndex();
adminIndex.AdminUsers = users;
adminIndex.AdminUserRoles = userRoles;
if (!String.IsNullOrEmpty(searchString))
{
adminIndex.AdminUsers = adminIndex.AdminUsers.Where(s => s.username.Contains(searchString));
}
return View(adminIndex);
}
查看
@model ComputerAidedDispatch.Models.AdminIndex
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm())
{
<p>
User: @Html.TextBox("SearchString")
<input type="submit" value="Search!" class="btn btn-default" />
</p>
}
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.username)
</th>
<th>
@Html.DisplayNameFor(model => model.firstName)
</th>
<th>
@Html.DisplayNameFor(model => model.lastName)
</th>
<th>
@Html.DisplayNameFor(model => model.email)
</th>
<th>
@Html.DisplayNameFor(model => model.loginAttempts)
</th>
<th>
@Html.DisplayNameFor(model => model.accountBanned)
</th>
<th>
@Html.DisplayName("Roles")
</th>
<th>
@Html.DisplayName("Actions")
</th>
<th></th>
</tr>
@foreach (var item in Model.AdminUsers.ToArray())
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.username)
</td>
<td>
@Html.DisplayFor(modelItem => item.firstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.lastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.email)
</td>
<td>
@Html.DisplayFor(modelItem => item.loginAttempts)
</td>
<td>
@Html.DisplayFor(modelItem => item.accountBanned)
</td>
<td>
@foreach(var role in Model.AdminUserRoles)
{
var userRole = role.UserRoles_roleName;
@Html.DisplayFor(modelItem => userRole)
}
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.userId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.userId })
</td>
</tr>
}
</table>
我感觉像 .ToArray() 行中的
Model.AdminUsers.ToArray()
可能是问题的一部分,但这阻止了我得到异常
MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
我没有想法,因此非常感谢任何帮助或建议! 提前致谢!
【问题讨论】:
标签: c# asp.net-mvc entity-framework model-view-controller