AspNetUsers' ID as Foreign key in separate table, one-to-one relationship

后端 未结 2 929
小鲜肉
小鲜肉 2020-12-30 03:14

I have looked up and down, tried all the different and various ways of being able to store a foreign key of the AspNetUser table in a separate Customer table. I\'m still new

2条回答
  •  感情败类
    2020-12-30 03:57

    In a one-to-one relation the "child" table, in your case Customer, should have the same primary key as the related table, i.e. the foreign key.

    The code sample you have supplied means that, in Customer you will have a PK named CustomerID which is different from UserId.

    This should work in your case (untested):

    public class Customer
    {
        [Key]
        public string UserId { get; set; }
    
        [ForeignKey("UserId")]
        public virtual ApplicationUser ApplicationUser { get; set; }
    }
    
    public class ApplicationUser : IdentityUser
    {
        public virtual Customer Customer { get; set; }
    }
    

    Edit:

    MSDN for ForeignKeyAttribute states:

    If you add the ForeigKey attribute to a foreign key property, you should specify the name of the associated navigation property. If you add the ForeigKey attribute to a navigation property, you should specify the name of the associated foreign key(s).

    I interpret this as that it should be possible to add the ForeignKey-attribute to either the navigation property or the foreign key property, and that either way should work, but apparently not. Moving it as per below should do the trick.

    public class Customer
    {
        [Key, ForeignKey("ApplicationUser")]
        public string UserId { get; set; }
        public virtual ApplicationUser ApplicationUser { get; set; }
    }
    
    public class ApplicationUser : IdentityUser
    {
        public virtual Customer Customer { get; set; }
    }
    

提交回复
热议问题