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

时间:2014-04-16 20:36:02

标签: c# asp.net entity-framework foreign-keys asp.net-identity

我使用Visual Studio 2013 Update 2 RC创建了Empty MVC(ASP.NET Web应用程序)项目 &安培;然后使用:

添加AspNet Identity Samples
  

PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre

我已启用并添加了迁移功能然后更新数据库,创建默认表。 enter image description here

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

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

所以我创建了2个课程Customer&使用数据注释对外部密钥进行分组和添加,如下所示:

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图表看起来也不错。项目建设得当。

enter image description here

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

enter image description here

现在我收到编译错误(在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();
}

enter image description here

错误详情: '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下拉列表:

enter image description here

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

2 个答案:

答案 0 :(得分:3)

实体框架非常智能,可以识别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; }
}

请查看thisthis文章了解详情。

答案 1 :(得分:2)

RTFE:您的ApplicationDbContext课程中没有属性ApplicationUsers。

只需添加:

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