【发布时间】:2016-08-22 08:01:58
【问题描述】:
我目前卡在一段返回异常的代码上:
控制器:
public ActionResult Edit (string userId)
{
AspNetUserRoles personRole;
if (userId == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
///error happens here during execution of Find() on table
personRole = tbls.AspNetUserRoles.Find(userId);
if (personRole == null)
{
return HttpNotFound();
}
return View(personRole);
}
VIEW(我通过它传递字符串 ID):
@model IEnumerable<WebApplication1.Models.MyViewModel>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.RoleId)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.RoleId)
</td>
<td>
@*I added null, so for the sake of routing*@
@Html.ActionLink("Edit", "Edit", "Home", new { id = item.Id }, null) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
型号:
public class MyViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string RoleId { get; set; }
}
public partial class AspNetUserRoles
{
[Key]
[Column(Order = 0)]
public string UserId { get; set; }
[Key]
[Column(Order = 1)]
public string RoleId { get; set; }
public virtual AspNetUsers AspNetUsers { get; set; }
}
}
public partial class AspNetUsers
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public AspNetUsers()
{
AspNetUserRoles = new HashSet<AspNetUserRoles>();
}
public string Id { get; set; }
[StringLength(256)]
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
[Required]
[StringLength(256)]
public string UserName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AspNetUserRoles> AspNetUserRoles { get; set; }
}
}
我想知道这里有什么问题。我可以在字符串 ID 上循环访问加入的 AspNetUsers 和 AspNetUserRoles,它会提供所有记录(针对 MyViewModel 键入)。然后在视图中,我希望能够访问针对 AspNetUserRoles 键入的特定记录并能够对其进行编辑,尽管现在这无关紧要,因为我在查询数据库时无法获得正确的记录。
我的想法是使用 @Html.ActionLink("Edit", "Edit", "Home", new { id = item.Id }, null) 的路由问题(检查了 URI 的样子,它是正确的意思控制器/动作/参数是好的,在调试字符串 Id 不为空时也是如此)或者更确切地说是 Find() 方法的问题,而它需要字符串参数或者我正在查询具有 2 个键的表的事实(尽管它只是一个不可靠的想法)。
任何线索都可能有用。
谢谢!
【问题讨论】:
标签: c# mysql asp.net-mvc foreign-keys key