我有以下模型类:
public class Farmer
{
public int ID { get; set; }
public Box Box { get; set; }
}
public class Apple
{
public int BoxID { get; set; }
public Box Box { get; set; }
public int Number { get { return (int)V2.X; } set { V2 = new Vector2(value, 0); } }
public Vector2 V2 {get;set;}
public Farmer Owner { get; set; }
}
public class Box : IEnumerable<Apple>
{
public int ID { get; set; }
public ICollection<Apple> Apples { get; set; }
public IEnumerator<Apple> GetEnumerator()
{
return Apples.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Apples.GetEnumerator();
}
}
当 Box 实现 IEnumerable<'Apple'> 时,影子属性 FarmerID 被添加到 Apple 表中:
migrationBuilder.AddColumn<int>(
name: "FarmerID",
table: "Apples",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Apples_FarmerID",
table: "Apples",
column: "FarmerID");
migrationBuilder.AddForeignKey(
name: "FK_Apples_Farmers_FarmerID",
table: "Apples",
column: "FarmerID",
principalTable: "Farmers",
principalColumn: "ID",
onDelete: ReferentialAction.Restrict);
当我注释掉 IEnumerable 实现时,预期的迁移是在没有 FarmerID 影子属性的情况下创建的。为什么会生成此阴影属性,如何删除它?(我试过忽略它,但后来我得到了 FarmerID1)。
我应该提到这是我的上下文类:
public class Context : DbContext
{
public DbSet<Farmer> Farmers { get; set; }
public DbSet<Apple> Apples { get; set; }
public DbSet<Box> Boxes { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"...");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Apple>()
.HasOne(a => a.Box)
.WithMany(a => a.Apples)
.IsRequired();
modelBuilder.Entity<Apple>()
.Ignore(a => a.V2)
.Ignore(a => a.Owner)
.HasKey(a => new { a.BoxID, a.Number });
}
}