簡體   English   中英

EF Core 1:1 關系?

[英]EF Core 1:1 Relation?

我想要的桌子看起來像這樣......

Identity  | Id (PK), Tag
Character | IdentityId (FK, PK), Health

字符表應該只引用標識表的一行......並且標識表不應引用任何其他 1:0。

我當前的 model 看起來像這樣......

    /// <summary>
    /// Represents an identity in our database. 
    /// </summary>
    public class Identity {

        public long Id { get; set; }
        public string Tag { get; set; }
    }
    
    /// <summary>
    /// Represents an character ingame with all his attributes. 
    /// </summary>
    public class Character {
        
        public Identity Identity { get; set; }

        public float Health { get; set; }
    }

    modelBuilder.Entity<Identity>(entity => {

          entity.ToTable("identity");
          entity.HasKey(e => e.Id);
    });
            
     modelBuilder.Entity<Character>(entity => {

          entity.ToTable("character");
          // entity.HasKey(e -> e.Identity.Id); DOES NOT WORK
          entity.Navigation(character => character.Identity).AutoInclude();
     });            

這樣做的問題是對角色內部身份的引用不算作主鍵……也不是外鍵。

e -> e.Identity.Id由於某種原因不起作用,並導致錯誤告訴我這是不可能的。

我希望 Character 中的Identity算作他的主鍵,同時仍然是對 Identity-Table(外鍵)中一行的引用。 然而,身份表不應引用該字符。

這可能嗎? 如果是這樣……怎么辦?

您可以在您的身份中創建一個屬性 class

 public class Identity {
        public long Id { get; set; }
        public string Tag { get; set; }

        public Character Character { get; set; }
    }

然后你的 model 變成

modelBuilder.Entity<Identity>()
                .HasOne(x => x.Character)
                .WithOne(x => x.Identity)
                .HasForeignKey<Character>(x => x.YourFkKey);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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