我有以下课程:
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 });
但是它似乎不起作用。
发布此帖子后,我解决了它。基本上,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 });