![](/img/trans.png)
[英]EntityFramework 4.1, context.Entities.Add sometimes set FK to NULL
[英]Cannot add FK using EntityFramework
我正在學習帶有Entity Framework
ASP.NET Core
,我正在嘗試在UserDetails
表中添加一個FK
。 這些是模型:
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)。
實際我想要將屬性UserId
添加為FK
該屬性必須綁定User
的Id
。 所以在ApplicationContext
類中我做了以下事情:
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 to 1
,所以我用WithOne
和分配UserDetail
其中包含UserDetails
對象。
最后我使用了HasForeignKey
但是當我輸入d.
編譯器不顯示任何屬性。
我做錯了什么? 也許我過分復雜了?
對於任何錯誤,我們深表歉意,並提前感謝您的任何解釋。
你能試試這個:
entity.HasOne(d => d.UserKey)
.WithOne(p => p.UserDetail)
.HasForeignKey<User>(b => b.Id);
要么
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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.