无法使用EntityFramework添加FK [英] Cannot add FK using EntityFramework
问题描述
我正在使用 Entity Framework
学习 ASP.NET Core
,并且尝试在 UserDetails中添加
FK
表.这些是模型:
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; }
}
表 User
是 Master
表,其中包含应用程序中的所有注册用户(我使用的是AspNetCore.Identity).
The table User
is the Master
table which contains all the registered user in my application (I'm using AspNetCore.Identity).
实际上我想将属性 UserId
作为 FK
添加,该属性必须绑定 User
的 Id
.因此,在 ApplicationContext
类中,我执行了以下操作:
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; }
}
我重写了 OnModelCreating
,并使用为 UserDetails
表定义的 ModelBuilder
某些属性的 MaxLength
.在 builder.Entity< UserDetails>
的最后一行中,我尝试指定 FK
与 HasOne =>创建关系.UserKey
,其中包含对象 User
.这种关系是 1比1
,因此我使用了 WithOne
并分配了 UserDetail
,其中包含了 UserDetails
对象.
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.
最后,我使用了 HasForeignKey
,但是当我键入 d.
时,编译器没有显示任何属性.
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.
推荐答案
以下代码将起作用:
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
});
这篇关于无法使用EntityFramework添加FK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!