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
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; }
}
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.
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):
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; }
}
Your ApplicationUser Class:
public virtual ICollection<Address> Addresses { get; set; }
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!