问题
I'm learning ASP.NET Core with Entity Framework and I'm trying to add an FK in my UserDetails table. These are the model:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual UserDetails UserDetail { get; set; }
}
public class UserDetails
{
public string UserId { get; set; }
public string Biography { get; set; }
public string Country { get; set; }
public Uri FacebookLink { get; set; }
public Uri TwitterLink { get; set; }
public Uri SkypeLink { get; set; }
public virtual User UserKey { get; set; }
}
The table User is the Master table which contains all the registered user in my application (I'm using AspNetCore.Identity).
Actual I want add as FK the property UserId which must bound the Id of User. So inside the ApplicationContext class I did the following:
public class DemoAppContext : IdentityDbContext<ApplicationUser>
{
public DemoAppContext(DbContextOptions<DemoAppContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<UserDetails>(entity =>
{
entity.Property(e => e.Biography).HasMaxLength(150);
entity.Property(e => e.Country).HasMaxLength(10);
entity.HasOne(d => d.UserKey)
.WithOne(p => p.UserDetail)
.HasForeignKey(d => d.???; <- problem here
});
}
public DbSet<User> Users { get; set; }
public DbSet<UserDetails> UserDetails { get; set; }
}
I overrided the OnModelCreating and using the ModelBuilder I defined for UserDetails table the MaxLength of some properties. In the last line of builder.Entity<UserDetails> I tried to assign the FK creating the relationship with HasOne => UserKey which contains the object User. The relationship is 1 to 1 so I used WithOne and assigned UserDetail which contains the UserDetails object.
At the end I used HasForeignKey but when I type d. the compiler doesn't show any properties.
What I did wrong? Maybe I overcomplicated the things?
Sorry for any errors, and thanks in advance for any explanation.
回答1:
The following code will work:
builder.Entity<UserDetails>(entity =>
{
entity.Property(e => e.Biography).HasMaxLength(150);
entity.Property(e => e.Country).HasMaxLength(10);
entity.HasOne(d => d.UserKey)
.WithOne(p => p.UserDetail)
.HasForeignKey<UserDetails>(x => x.UserId); //???; < -problem here
});
回答2:
Can you try this:
entity.HasOne(d => d.UserKey)
.WithOne(p => p.UserDetail)
.HasForeignKey<User>(b => b.Id);
or
public class UserDetails
{
[ForeignKey(nameof(UserKey))]
public string UserId { get; set; }
public string Biography { get; set; }
public string Country { get; set; }
public Uri FacebookLink { get; set; }
public Uri TwitterLink { get; set; }
public Uri SkypeLink { get; set; }
public virtual User UserKey { get; set; }
}
来源:https://stackoverflow.com/questions/52310518/cannot-add-fk-using-entityframework