How to add a Foreign key in Customer table (CreatedBy column) for AspNetUser table (Id column) in ASP.NET MVC 5 Identity 2.0 using Code First

asp.net asp.net-identity c# entity-framework foreign-keys

Accepted Answer

RTFE: ApplicationUsers is not a property on yourApplicationDbContext class.

Simply add:

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
2
4/17/2014 11:38:18 AM

Popular Answer

Entity Framework is capable of identifying common names for keys and IDs. Therefore, you would follow these steps to add a foreign key:

public class Customer
{
    public string CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public int ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; } 
}

According to convention, it corresponds to a class name plus "oeId" as a foreign key. If you prefer not to follow this protocol, you can useForeignKey Data annotation to assist EF in determining what the foreign key should be:

public class Customer
{
    public string CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public int UserId { get; set; }
    [ForeignKey("UserId")]
    public ApplicationUser ApplicationUser { get; set; }
}

For further information, see the this and this articles.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow