简体   繁体   中英

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.

My current model is looking like this...

    /// <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.

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 ). The identity table however should not reference the character.

Is this possible? If so... how?

You can create a property in your Identity class

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

        public Character Character { get; set; }
    }

then your model become

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM