从AspNetUser.Email
视图中显示Customer
时,出现此错误。我正在.Include(AspNetUser)
上执行CustomerController
并引用AspNetUser
所在的数据库表名Email
。不确定我在这里缺少什么,但我需要能够从AspNetUser.Email
视图中呼叫Customer
。
我的ApplicationUser
来自我IdentityModel
,其中包含以下内容。
在我的Customer
表中,我有一个Customer.UserId
列,它是AspNetUser.Id
列的外键。
客户模式
namespace DemoPool.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Customer")]
public partial class Customer
{
[StringLength(128)]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser AspNetUser { get; set; }
}
}
客户控制器
// GET: Customers
[Authorize(Roles = "Admin, User")]
public ActionResult Index()
{
var customers = db.Customers.Include(c => c.AspNetUser);
return View(customers.ToList());
}
客户视图
@model IEnumerable<DemoPool.Models.Customer>
<table class="table">
<tr>
<td>
@Html.DisplayFor(modelItem => item.AspNetUser.Email)
</td>
</tr>
</table>
IdentityModel
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace DemoPool.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit https://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DemoPoolEntities", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
答案 0 :(得分:2)
通过在[ForeignKey]
类中的虚拟属性上指定Customer
属性,您基本上告诉EF您有一个DB表,并且该关系将被解析。如果我正确理解了这个问题,那么你需要AspNetUser
实体类来实现这一点。