How to add a foreign key reference to ASP.Net MVC 5 Identity?

后端 未结 3 1869
無奈伤痛
無奈伤痛 2021-01-30 04:16

I have a new ASP.NET MVC 5.1 project using the ASP.Net Identity. It seems reliable and promise, but today i spend almost 9 hours to do a simple things if using SQL.

My p

相关标签:
3条回答
  • 2021-01-30 04:48

    You can do like this. because sometime you may need 1-1 connection

     public class AnotherTable
        {
            [Key]
            public string UserId { get; set; }
    
            [ForeignKey("UserId")]
            public virtual ApplicationUser User { get; set; }
        }
    
    0 讨论(0)
  • 2021-01-30 04:49

    Thanks you Gábor Plesz for comment above.

    I found the solution.

    The ApplicationUser class who inherit IdentityUser (which create AspNetUsers table) should create a ICollection property of the child class (child table).

    e.g.

    public virtual ICollection<ToDo> ToDoes { get; set; }
    

    So the ToDo class can be reference to ApplicationUser

    Highly recommend have a look the sample as Gábor Plesz said.

    enter image description here

    0 讨论(0)
  • 2021-01-30 04:58

    If you really wanna create a table named Address instead of creating a property named Address to generated as a column into AspNetUsers table do the following (obs: in this case i am assuming that a user can have many address):

    1. At your Address class:

      public class Address
      {
          public string MyAddress { get; set; }
      
          // referencing the AspNetUsers table ( ApplicationUser.cs)
          public string UserId { get; set; }
          public virtual ApplicationUser User { get; set; }
      }
      
    2. Your ApplicationUser Class:

      public virtual ICollection<Address> Addresses { get; set; }
      
    3. Within your DBContext in OnModelCreating method do the following ( fluent API ):

      builder.Entity<Address>()
                    .HasOne(c => c.User)
                    .WithMany(x => x.Addresses)
                    .HasForeignKey(f => f.UserId)
                    .HasConstraintName("UserId")
                    .OnDelete(DeleteBehavior.Cascade)
                    .IsRequired();
      

    OBS: Don´t forget adding above the OnModelCreating method this line of code:

    public DbSet<Address> Addresses { get; set; }
    

    After it run those commands within your Package Manager Console:

    Add-Migrations UserAddress
    

    and after:

    Update-Database. 
    

    But, if you wanna just inclued a new property to the AspNet Users just create at your ApplicationUser.cs file/class this property:

    public class ApplicationUser : IdentityUser
        {
            public string Address { get; set; }
        }
    

    and run the same commands for your PMC:

    Add-Migration UserAddress
    

    after:

    Update-Database
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题