SqlException:无效的对象名称'dbo.ApplicationUsers'

时间:2018-02-04 15:23:10

标签: c# sql-server asp.net-mvc entity-framework

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();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

通过在[ForeignKey]类中的虚拟属性上指定Customer属性,您基本上告诉EF您有一个DB表,并且该关系将被解析。如果我正确理解了这个问题,那么你需要AspNetUser实体类来实现这一点。