简体   繁体   English

EF Core 1:1 关系?

[英]EF Core 1:1 Relation?

The tables i want are looking like this...我想要的桌子看起来像这样......

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

The character table should reference exactly one single row of the identity table... and the identity table should not reference anything else 1:0.字符表应该只引用标识表的一行......并且标识表不应引用任何其他 1:0。

My current model is looking like this...我当前的 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();
     });            

The problem with this is that the reference to the identity inside the character does not count as an primary key... neither a foreign key.这样做的问题是对角色内部身份的引用不算作主键……也不是外键。

e -> e.Identity.Id does not work for some reason and results in an error telling me that this is not possible. e -> e.Identity.Id由于某种原因不起作用,并导致错误告诉我这是不可能的。

I want that the Identity inside the Character counts as his primary key, while still being a reference to an row inside the Identity-Table ( Foreign key ).我希望 Character 中的Identity算作他的主键,同时仍然是对 Identity-Table(外键)中一行的引用。 The identity table however should not reference the character.然而,身份表不应引用该字符。

Is this possible?这可能吗? If so... how?如果是这样……怎么办?

You can create a property in your Identity class您可以在您的身份中创建一个属性 class

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

        public Character Character { get; set; }
    }

then your model become然后你的 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