如何在EF Core中具有外键和其他属性的复合键?

问题描述 投票:1回答:1

我有以下课程:

    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; }
    }

我想要得到一个诸如这样的模式:

Apple:主(复合)键: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个回答
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 });
© www.soinside.com 2019 - 2024. All rights reserved.