I'm trying to create a one-to-many relationship between the asp.net identity table "aspnetusers" and my own "application" table. The problem is that the aspnetusers table primary key does not have a name prefixing it - it is just named "Id". I'd like to create a name for it such as ApplicationUserId, so that I can avoid confusion when using it for binding purposes. How can I do this?
public class Application
{
public int ApplicationId { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
//**Need the aspnetuser table Id property here for my foreign key and would like to name it ApplicationUserId - how do I do this?
If you just add a virtual property to your Application
class, EF should take care of naming the FK in the database and you'd just be accessing that navigation property from your code, ie you won't need to know the FK column name in your code. But if you insist on specifying it, you can try something like this in your class:
public class Application
{
// other properties
public int ApplicationUserId { get; set; }
public virtual User User {get; set; }
}
and in your DbContext class use fluent API and override OnModelCreating
method with something like this:
public class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Application>()
.HasRequired(x => x.User)
.WithMany()
.HasForeignKey(k => k.ApplicationUserId);
}
}
NOTE: I didn't test this, so customize this to fit your needs specifically.
Could you do something like
public class Application
{
public int ApplicationId { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[ForeignKey("aspnetusers")]
[Column("Id")]
public int ApplicationUserId { get; set; }
public virtual aspnetusers aspnetusers {get; set; }
....
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.