我是mvc的新手并试图了解我做错了什么我创建了一个Dbcontaxt
类
public class DataBaseContext : DbContext
{
public DataBaseContext()
: base("DefaultConnection")
{
}
public DbSet<Membership> Membership { get; set; }
public DbSet<OAuthMembership> OAuthMembership { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Category> Categorys { get; set; }
public DbSet<SubCategory> SubCategorys { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Color> Colors { get; set; }
public DbSet<Size> Sizes { get; set; }
public DbSet<Company> Companys { get; set; }
public DbSet<UsersInRoles> UsersInRoles { get; set; }
}
}
我创建了一个模型类来创建一个强类型视图
[Bind(Exclude = "AddUserToRoleID")]
public class AddUserToRole
{
[ScaffoldColumn(false)]
public int AddUserToRoleID { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[Display(Name = "Role name")]
public string RoleName { get; set; }
}
}
在控制器中我试图通过添加视图来创建详细信息视图,并选择AddUserToRole
作为强类型视图的模型
public ActionResult Details(int id = 0)
{
var UserInRole = db.UserProfiles
.Join(db.UsersInRoles,
u => u.UserId,
uir => uir.UserId,
(u, uir) => new {u = u,uir = uir})
.Join(db.Roles,
temp0 => temp0.uir.RoleId,
r => r.RoleId,
(temp0, r) => new { temp0 = temp0,r = r })
.Where(temp1 => (temp1.temp0.u.UserId == id))
.Select(temp1 => new AddUserToRole {
AddUserToRoleID = temp1.temp0.u.UserId,
UserName = temp1.temp0.u.UserName,
RoleName = temp1.r.RoleName
});
return View(UserInRole);
}
它给我这个错误
The model item passed into the dictionary is of type
'System.Data.Entity.Infrastructure.DbQuery`1[SeniorProject.Models.AddUserToRole]', but
this dictionary requires a model item of type 'SeniorProject.Models.AddUserToRole'.
当我施放return View((UsersInRoles)UserInRole);
时,它会给我这个错误
Unable to cast object of type
'System.Data.Entity.Infrastructure.DbQuery`1[SeniorProject.Models.AddUserToRole]'
to type'SeniorProject.Models.UsersInRoles'.
和视图
@model SeniorProject.Models.AddUserToRole
@{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<fieldset>
<legend>AddUserToRole</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.UserName)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.UserName)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.RoleName)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.RoleName)
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { id=Model.AddUserToRoleID }) |
@Html.ActionLink("Back to List", "Index")
</p>
在这种情况下该怎么做?
答案 0 :(得分:13)
你需要实现它。将FirstOrDefault()放在查询的末尾
var materializedUser = UserInRole.SingleOrDefault();
return View(materializedUser);
编辑:跟随pjotr评论用SingleOrDefault()替换FirstOrDefault()