【问题标题】:How can I have a composite key of a foreign key and other properties in EF Core?如何在 EF Core 中拥有外键和其他属性的复合键?
【发布时间】:2020-06-07 20:52:08
【问题描述】:

我有以下课程:

    public class Apple
    {
        public int BoxID { get; set; }

        [ForeignKey("BoxID")]
        public Box Box{ get; set; }

        public int R { get => Color.R; set => Color = new Color (value, Color.G, Color.B); }

        public int G { get => Color.G set => Color = new Color (Color.R, value, Color.B); }

        public int B { get => Color.B set => Color = new Color (Color.R, Color.G, value); }

        [NotMapped]
        public Color Color { get; set; }    
    }

    public class Box
    {
        [Key]
        public int ID { get; set; }

        public IEnumerable<Apple> Apples { get; set; }
    }

我想要的是得到一个架构,例如:

苹果:
主(复合)键:BoxID(外键)、R、G、B

盒子:
主键:ID

我尝试过的:

        modelBuilder.Entity<Apple>()
            .HasKey(a=> new { a.BoxID, a.R, a.G, a.B });

但它似乎不起作用。

【问题讨论】:

    标签: c# entity-framework entity-framework-core data-annotations ef-fluent-api


    【解决方案1】:

    好吧,刚刚发布这个我就解决了。 基本上,Fluent API 允许我们对模型构建器进行多次调用:

            modelBuilder.Entity<Apple>()
                .HasOne(a=> a.Box)
                .WithMany(box => box.Apples)
                .HasForeignKey(a=> a.BoxID)
                .IsRequired();
    
            modelBuilder.Entity<Apple>()
                .HasKey(a=> new { a.BoxID, a.R, a.G, a.B });
    

    【讨论】:

      猜你喜欢
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2019-11-26
      • 2011-10-17
      • 1970-01-01
      相关资源
      最近更新 更多