实体框架与ASP.NET标识表的一对一关系

时间:2018-04-08 13:20:57

标签: c# asp.net-mvc entity-framework asp.net-identity ef-fluent-api

我能够在AspNetUsers表和我的域模型Employee之间建立一对一的关系:

public class Employee
{
    public int Id { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    public ApplicationUser User { get; set; }

    [Required]
    [Display(Name = "Employee")]
    public string UserId { get; set; }               
}

这是ApplicationUser类:

public class ApplicationUser : IdentityUser
{
    public Employee Employee { get; set; }

    public ApplicationUser()
    {
        Employee = new Employee();
    }
}

这是我在配置类中与FluentAPI一起使用的一对一关系的配置:

public class EmployeeConfiguration: EntityTypeConfiguration<Employee>
{
    public EmployeeConfiguration()
    {

        HasRequired(c => c.User)
            .WithRequiredDependent(u => u.Employee)
            .WillCascadeOnDelete(false);
    }
}

我的问题是,当我运行迁移时,创建表会生成一个额外的User_Id列,这将是外键,但我想要的是使用我在我的域模型Employee中添加的UserId属性作为外来因为我需要稍后使用该属性。

这是迁移:

 public override void Up()
    {
        CreateTable(
            "dbo.Employees",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Name = c.String(nullable: false, maxLength: 50),
                    UserId = c.String(nullable: false), //I want this 
                    //property as the foreign key and not User_Id
                    User_Id = c.String(nullable: false, maxLength: 128),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.AspNetUsers", t => t.User_Id)
            .Index(t => t.User_Id);

    }

关于如何使域模型的UserId属性成为外键而不是User_Id的一些想法。 以前我能够与其他实体建立一对一的关系,但我不能使用ASP.NET身份实体。

0 个答案:

没有答案