简体   繁体   English

MVC 5代码优先实体框架的可选关系将PK与FK分开

[英]MVC 5 Code First Entity Framework Optional Relationship seperate PK from FK

I want to configure a 'one to zero or one' relationship between ApplicationUser table and User table whereby ApplicationUser table is the principal and Student is the dependent. 我想在ApplicationUser表和User表之间配置“一对零或一个”关系,其中ApplicationUser表是主体,而Student是从属。 However, I would like to have a seperate Primary key for Student table and a Foreign Key that references ApplicationUser table's ApplicationUserID . 但是,我希望有一个单独的StudentPrimary key和一个引用ApplicationUser表的ApplicationUserIDForeign Key

public class Student
{
    [Key]
    [Required]
    [StringLength(10)]
    public string StudentCode { get; set; }

    [Required]
    [StringLength(15)]
    [Column(TypeName = "varchar")]
    public string ContactNum { get; set; }

    public virtual ApplicationUser User { get; set; }

    [ForeignKey("User")]
    public string ApplicationUserID { get; set; }
}

public class ApplicationUser : IdentityUser
{
    public virtual Students Students { get; set; }
}

I've problem migrating this code as it raises an error of: 我在迁移此代码时遇到问题,因为它引起以下错误:

Student_User_Source: : Multiplicity is not valid in Role 'Student_User_Source' in relationship 'Student_User'. Student_User_Source::多重性在关系“ Student_User”中的角色“ Student_User_Source”中无效。 Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'. 因为从属角色属性不是关键属性,所以从属角色多重性的上限必须为'*'。

So how do I configure this? 那么我该如何配置呢?

For one to one or zero relation do the folowing 对于一对一或零关系,请遵循

Class ApplicationUser
{
[Key]
Int ApplicationUserId

// other properties
}

Class Student
{
[Key]
Int StudentId

Int? AppUserId

[ForeignKey("AppUserId")]
Virtual ApplicationUser AppUser
}

Now a Student can have one or Zero ApplicationUser 现在,一个学生可以拥有一个或零个ApplicationUser

Plus you had the annotation of the foreign key reversed .. it is possible that this was the only problem 另外,您将外键的注释反转了..这可能是唯一的问题

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

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