繁体   English   中英

如何使用Code First在ASP.NET MVC 5 Identity 2.0中为AspNetUser表(Id列)在Customer表(CreatedBy列)中添加外键

[英]How to add a Foreign key in Customer table (CreatedBy column) for AspNetUser table (Id column) in ASP.NET MVC 5 Identity 2.0 using Code First

我使用Visual Studio 2013 Update 2 RC创建了Empty MVC(ASP.NET Web应用程序)项目,然后使用以下命令添加了AspNet Identity Samples:

PM>安装包Microsoft.AspNet.Identity.Samples -Pre

我已启用并添加了迁移,然后更新了数据库,这些数据库创建了默认表。 在此输入图像描述

我想创建一个Customer表,其中包含2列作为外键:

  • 组表(GroupId列)
  • AspNetUsers表(Id列)

所以我创建了2个Customer&Group类,并使用Data-annotations添加了外键,如下所示:

namespace IdentitySample.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://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("DefaultConnection", throwIfV1Schema: false)
        {
        }

        static ApplicationDbContext()
        {
            // Set the database intializer which is run once during application start
            // This seeds the database with admin user credentials and admin role
            Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<Group> Groups { get; set; }
    }

    public class Customer
    {
        public int CustomerId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public int GroupId { get; set; }
        public string CreatedBy { get; set; }



        [ForeignKey("GroupId")]
        public Group Groups { get; set; }

        [ForeignKey("CreatedBy")]
        public ApplicationUser ApplicationUsers { get; set; }
    }

    public class Group
    {
        public int GroupId { get; set; }
        public string GroupName { get; set; }
    }
}

一切似乎都很好,使用EF Power工具创建的ApplicationDbContext.edmx图表看起来很好并且项目构建正常。

在此输入图像描述

然后我使用“带有视图的MVC 5控制器,使用实体框架”脚手架模板添加了CustomersController。

在此输入图像描述

现在我收到编译错误(在db.ApplicationUsers上)

// GET: Customers/Create
public ActionResult Create()
{
    ViewBag.CreatedBy = new SelectList(db.ApplicationUsers, "Id", "Email");
    ViewBag.GroupId = new SelectList(db.Groups, "GroupId", "GroupName");
    return View();
}

在此输入图像描述

错误详细信息: 'IdentitySample.Models.ApplicationDbContext'不包含'ApplicationUsers'的定义,并且没有扩展方法'ApplicationUsers'接受类型'IdentitySample.Models.ApplicationDbContext'的第一个参数(您是否缺少using指令或装配参考?)

当我在ApplicationDbContext添加以下代码时

public DbSet<ApplicationUser> ApplicationUsers { get; set; }

我收到错误:

不支持每种类型的多个对象集。 对象集'ApplicationUsers'和'Users'都可以包含'IdentitySample.Models.ApplicationUser'类型的实例

我想将CreatedBy添加为AspNetUsers的外键,使用该模板生成类似于GroupId下拉列表的CreatedBy下拉列表:

在此输入图像描述

我们如何将Identity生成的表与其他用户创建的表一起使用,其中用户创建的表具有对Identity生成的表的外键引用。 并使用“带有视图的MVC 5控制器,使用实体框架”获得一流的脚手架代码生成体验?
(与我们对Customers&Groups表的相似,其中Customers表具有GroupId外键引用)

实体框架足够智能,可以识别ID /密钥的传统名称。 因此,为了添加外键,您可以这样做:

public class Customer
{
    public string CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public int ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; } 
}

按照惯例,它将类名加上“Id”作为外键。 如果您不想使用此约定,那么您可以使用ForeignKey数据批注来帮助EF了解应该是什么外键:

public class Customer
{
    public string CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public int UserId { get; set; }
    [ForeignKey("UserId")]
    public ApplicationUser ApplicationUser { get; set; }
}

看看这个这个文章获取更多信息。

RTFE:您的ApplicationDbContext类上没有属性ApplicationUsers。

只需添加:

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM