Reputation: 952
When displaying the AspNetUser.Email
from my Customer
view I get this error. I am doing a .Include(AspNetUser)
on the CustomerController
and referencing the database table name AspNetUser
where Email
is coming from. Not sure what I'm missing here but I need to be able to call AspNetUser.Email
from the Customer
view.
MyApplicationUser
comes from my IdentityModel
which I have included below.
In my Customer
table I have a Customer.UserId
column which is a foreign key to the AspNetUser.Id
column.
Customer Model
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; }
}
}
Customer Controller
// GET: Customers
[Authorize(Roles = "Admin, User")]
public ActionResult Index()
{
var customers = db.Customers.Include(c => c.AspNetUser);
return View(customers.ToList());
}
Customer View
@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();
}
}
}
Upvotes: 1
Views: 2797
Reputation: 4802
By specifying [ForeignKey]
attribute on a virtual property in your Customer
class you are basically telling EF that you have a DB table for it and that the relation will be resolved. If I understand this problem correctly, then you need AspNetUser
entity class for this to work.
Upvotes: 2