【问题标题】:EF Core 1:1 Relation?EF Core 1:1 关系?
【发布时间】:2021-11-25 00:54:15
【问题描述】:

我想要的表格是这样的......

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

字符表应该准确引用标识表的一行...并且标识表不应该引用任何其他内容 1:0。

我现在的模型是这样的......

    /// <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 -&gt; e.Identity.Id 由于某种原因无法正常工作,并导致出现错误,告诉我这是不可能的。

我希望 Character 中的 Identity 算作他的主键,同时仍然是对 Identity-Table 中一行的引用(外键)。然而,身份表不应引用该字符。

这可能吗?如果是……怎么办?

【问题讨论】:

  • 没有1:0 关系。那是 1:1
  • @PanagiotisKanavos 这种关系怎么称呼? :o 我认为它是 1:0...如果不是我需要编辑我的标题
  • 这是 1:1 的关系。
  • @PanagiotisKanavos 但是身份不应该也不应该指代角色......所以它真的是1:1的关系吗?
  • 两个数据库字段的值不一样吗? does not refer the character. 这与类中的字段无关。关系在表之间,没有父子关系

标签: c# mysql entity-framework entity-framework-core


【解决方案1】:

你可以在你的 Identity 类中创建一个属性

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

        public Character Character { get; set; }
    }

那么你的模型就变成了

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

【讨论】:

  • HasForeignKey 需要一个泛型类型参数来指示哪个实体是依赖的。
  • 这是错误的一面。 Identity 是独立的,Character.Id 应该是 FK。这使得这是一个共享主键关联
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
  • 2011-08-26
  • 2012-12-10
  • 1970-01-01
  • 2015-07-06
相关资源
最近更新 更多