【问题标题】:How create one-to-one relationship between identity user and my Employee table如何在身份用户和我的 Employee 表之间创建一对一的关系
【发布时间】:2015-09-25 14:27:06
【问题描述】:

我正在尝试在我的 AspNetUser(ApplicationUser 类)表和我的 Employee 表之间创建一对一的关系。

问题是:

  • 我的应用程序与我的 Employee 表有很多关系,所以我无法创建复合键。

我尝试过的:

  • 我尝试使用唯一索引,但实体框架不支持索引。
  • 我尝试将外键放在 ApplicationUser 类中,但我猜 asp.net 标识不支持 AspNetUsers 表中的复合键。

这是我期望实现的示例:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
    {
        public ApplicationUser()
            : base()
        {
            PreviousUserPasswords = new List<PreviousPassword>();
        }
        public virtual IList<PreviousPassword> PreviousUserPasswords { get; set; }

        public virtual Employee Employee { get; set; }
    }

    [Table("EMPLOYEE")]
    public class Employee
    {
        [Key, Column("ID")]
        public int Id { get; set; }
        [Column("ID_IDIOM")]
        public int IdIdiom { get; set; }
        [Column("USER_LOGIN")]
        [Required]
        [StringLength(50)]
        public string UserName { get; set; }
        [Column("NAME")]
        [Required]
        [StringLength(100)]
        public string Name { get; set; }
        [Column("EMAIL")]
        [Required]
        [StringLength(100)]
        public string Email { get; set; }
        [Column("ACTIVE")]
        public bool Active { get; set; }
        [Column("EMPLOYEE_TYPE")]
        public short EmployeeType { get; set; }
        [Column("SHOW_TUTORIAL")]
        public bool ShowTutorial { get; set; }

        public ApplicationUser User { get; set; }
    }

任何想法都会有很大帮助。

PS.:对不起,我的英语不好。

【问题讨论】:

  • 这些是在不同的上下文中吗?如果您的应用程序上下文继承自身份上下文,那么您应该能够在其中引用员工(外键,而不是复合键)。如果它们是分开的,那么您将需要在您的非身份上下文中创建一个 ApplicationUser 类。
  • @SteveGreene 这是相同的上下文。但是当我在不使用复合键的情况下创建外键时,EF 认为这是一对多的关系。
  • 谢谢伙计。有效。但是在我在一个空数据库中运行我的应用程序之后才工作,然后我将身份表移动到我现有的数据库中。我建议您将您的评论写成答案,以便我可以接受。

标签: entity-framework-6 asp.net-identity-2


【解决方案1】:

如果您的应用程序上下文继承自 IdentityDbContext,则可以使用 fluent api 进行配置:

modelBuilder.Entity<Employee>()
   .HasRequired(e => e.User)
   .WithRequiredDependent(u => u.Employee);

https://msdn.microsoft.com/en-us/data/jj591620.aspx?f=255&MSPPError=-2147217396#RequiredToRequired

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 2020-09-04
    • 2019-02-17
    • 2023-03-25
    • 2019-09-22
    相关资源
    最近更新 更多