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

后端 未结 3 1870
無奈伤痛
無奈伤痛 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: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
      Addresses { get; set; }
    3. Within your DBContext in OnModelCreating method do the following ( fluent API ):

      builder.Entity
      () .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
    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!

提交回复
热议问题