簡體   English   中英

無法使用EntityFramework添加FK

[英]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; }
}

UserMaster表,其中包含我的應用程序中的所有注冊用戶(我使用的是AspNetCore.Identity)。

實際我想要將屬性UserId添加為FK該屬性必須綁定UserId 所以在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. 編譯器不顯示任何屬性。

我做錯了什么? 也許我過分復雜了?

對於任何錯誤,我們深表歉意,並提前感謝您的任何解釋。

以下代碼將起作用:

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
});

在此輸入圖像描述

你能試試這個:

        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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM